"""Add SEO metrics tables for GSC, Bing, and Umami data sync.

Three tables:
  - seo_search_metrics  — daily search data per page+query (GSC + Bing)
  - seo_analytics_metrics — daily page analytics (Umami)
  - seo_sync_log — tracks sync state per source
"""


def up(conn):
    # ── 1. Search metrics (GSC + Bing) ─────────────────────────────────
    conn.execute("""
        CREATE TABLE IF NOT EXISTS seo_search_metrics (
            id            INTEGER PRIMARY KEY AUTOINCREMENT,
            source        TEXT NOT NULL,
            metric_date   TEXT NOT NULL,
            page_url      TEXT NOT NULL,
            query         TEXT,
            country       TEXT,
            device        TEXT,
            clicks        INTEGER NOT NULL DEFAULT 0,
            impressions   INTEGER NOT NULL DEFAULT 0,
            ctr           REAL,
            position_avg  REAL,
            created_at    TEXT NOT NULL DEFAULT (datetime('now'))
        )
    """)
    # COALESCE converts NULLs to '' for unique index (SQLite treats
    # NULL as distinct in UNIQUE constraints, causing duplicate rows)
    conn.execute("""
        CREATE UNIQUE INDEX IF NOT EXISTS idx_seo_search_dedup
        ON seo_search_metrics(
            source, metric_date, page_url,
            COALESCE(query, ''), COALESCE(country, ''), COALESCE(device, '')
        )
    """)
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_seo_search_date"
        " ON seo_search_metrics(metric_date)"
    )
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_seo_search_page"
        " ON seo_search_metrics(page_url)"
    )

    # ── 2. Analytics metrics (Umami) ───────────────────────────────────
    conn.execute("""
        CREATE TABLE IF NOT EXISTS seo_analytics_metrics (
            id               INTEGER PRIMARY KEY AUTOINCREMENT,
            metric_date      TEXT NOT NULL,
            page_url         TEXT NOT NULL,
            pageviews        INTEGER NOT NULL DEFAULT 0,
            visitors         INTEGER NOT NULL DEFAULT 0,
            bounce_rate      REAL,
            time_avg_seconds INTEGER,
            created_at       TEXT NOT NULL DEFAULT (datetime('now'))
        )
    """)
    conn.execute("""
        CREATE UNIQUE INDEX IF NOT EXISTS idx_seo_analytics_dedup
        ON seo_analytics_metrics(metric_date, page_url)
    """)
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_seo_analytics_date"
        " ON seo_analytics_metrics(metric_date)"
    )

    # ── 3. Sync log ────────────────────────────────────────────────────
    conn.execute("""
        CREATE TABLE IF NOT EXISTS seo_sync_log (
            id           INTEGER PRIMARY KEY AUTOINCREMENT,
            source       TEXT NOT NULL,
            status       TEXT NOT NULL,
            rows_synced  INTEGER NOT NULL DEFAULT 0,
            error        TEXT,
            started_at   TEXT NOT NULL,
            completed_at TEXT,
            duration_ms  INTEGER
        )
    """)
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_seo_sync_source"
        " ON seo_sync_log(source, started_at)"
    )
