"""Initial schema baseline — all tables as of migration 0012."""


def up(conn):
    # Users
    conn.execute("""
        CREATE TABLE IF NOT EXISTS users (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            email TEXT UNIQUE NOT NULL,
            name TEXT,
            created_at TEXT NOT NULL,
            updated_at TEXT,
            last_login_at TEXT,
            deleted_at TEXT
        )
    """)
    conn.execute("CREATE INDEX IF NOT EXISTS idx_users_email ON users(email)")
    conn.execute("CREATE INDEX IF NOT EXISTS idx_users_deleted ON users(deleted_at)")

    # User Roles (RBAC)
    conn.execute("""
        CREATE TABLE IF NOT EXISTS user_roles (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
            role TEXT NOT NULL,
            granted_at TEXT NOT NULL DEFAULT (datetime('now')),
            UNIQUE(user_id, role)
        )
    """)
    conn.execute("CREATE INDEX IF NOT EXISTS idx_user_roles_user ON user_roles(user_id)")
    conn.execute("CREATE INDEX IF NOT EXISTS idx_user_roles_role ON user_roles(role)")

    # Billing Customers
    conn.execute("""
        CREATE TABLE IF NOT EXISTS billing_customers (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            user_id INTEGER NOT NULL UNIQUE REFERENCES users(id),
            provider_customer_id TEXT NOT NULL,
            created_at TEXT NOT NULL DEFAULT (datetime('now'))
        )
    """)
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_billing_customers_user ON billing_customers(user_id)"
    )
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_billing_customers_provider"
        " ON billing_customers(provider_customer_id)"
    )

    # Auth Tokens (magic links)
    conn.execute("""
        CREATE TABLE IF NOT EXISTS auth_tokens (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            user_id INTEGER NOT NULL REFERENCES users(id),
            token TEXT UNIQUE NOT NULL,
            expires_at TEXT NOT NULL,
            used_at TEXT,
            created_at TEXT DEFAULT CURRENT_TIMESTAMP
        )
    """)
    conn.execute("CREATE INDEX IF NOT EXISTS idx_auth_tokens_token ON auth_tokens(token)")
    conn.execute("CREATE INDEX IF NOT EXISTS idx_auth_tokens_user ON auth_tokens(user_id)")

    # Subscriptions
    conn.execute("""
        CREATE TABLE IF NOT EXISTS subscriptions (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            user_id INTEGER NOT NULL REFERENCES users(id),
            plan TEXT NOT NULL DEFAULT 'free',
            status TEXT NOT NULL DEFAULT 'free',
            provider_subscription_id TEXT,
            current_period_end TEXT,
            created_at TEXT NOT NULL,
            updated_at TEXT
        )
    """)
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_subscriptions_user ON subscriptions(user_id)"
    )
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_subscriptions_provider"
        " ON subscriptions(provider_subscription_id)"
    )

    # API Keys
    conn.execute("""
        CREATE TABLE IF NOT EXISTS api_keys (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            user_id INTEGER NOT NULL REFERENCES users(id),
            name TEXT NOT NULL,
            key_hash TEXT UNIQUE NOT NULL,
            key_prefix TEXT NOT NULL,
            scopes TEXT DEFAULT 'read',
            created_at TEXT NOT NULL,
            last_used_at TEXT,
            deleted_at TEXT
        )
    """)
    conn.execute("CREATE INDEX IF NOT EXISTS idx_api_keys_hash ON api_keys(key_hash)")
    conn.execute("CREATE INDEX IF NOT EXISTS idx_api_keys_user ON api_keys(user_id)")

    # API Request Log
    conn.execute("""
        CREATE TABLE IF NOT EXISTS api_requests (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            user_id INTEGER NOT NULL REFERENCES users(id),
            endpoint TEXT NOT NULL,
            method TEXT NOT NULL,
            created_at TEXT NOT NULL
        )
    """)
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_api_requests_user ON api_requests(user_id)"
    )
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_api_requests_date ON api_requests(created_at)"
    )

    # Rate Limits
    conn.execute("""
        CREATE TABLE IF NOT EXISTS rate_limits (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            key TEXT NOT NULL,
            timestamp TEXT NOT NULL
        )
    """)
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_rate_limits_key ON rate_limits(key, timestamp)"
    )

    # Background Tasks
    conn.execute("""
        CREATE TABLE IF NOT EXISTS tasks (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            task_name TEXT NOT NULL,
            payload TEXT,
            status TEXT NOT NULL DEFAULT 'pending',
            run_at TEXT NOT NULL,
            retries INTEGER DEFAULT 0,
            error TEXT,
            created_at TEXT NOT NULL,
            completed_at TEXT
        )
    """)
    conn.execute("CREATE INDEX IF NOT EXISTS idx_tasks_status ON tasks(status, run_at)")

    # Scenarios (core domain entity)
    conn.execute("""
        CREATE TABLE IF NOT EXISTS scenarios (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            user_id INTEGER NOT NULL REFERENCES users(id),
            name TEXT NOT NULL DEFAULT 'Untitled Scenario',
            state_json TEXT NOT NULL,
            location TEXT,
            is_default INTEGER DEFAULT 0,
            created_at TEXT NOT NULL,
            updated_at TEXT,
            deleted_at TEXT
        )
    """)
    conn.execute("CREATE INDEX IF NOT EXISTS idx_scenarios_user ON scenarios(user_id)")

    # Lead requests
    conn.execute("""
        CREATE TABLE IF NOT EXISTS lead_requests (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            user_id INTEGER REFERENCES users(id),
            lead_type TEXT NOT NULL,
            scenario_id INTEGER REFERENCES scenarios(id),
            location TEXT,
            court_count INTEGER,
            budget_estimate INTEGER,
            message TEXT,
            status TEXT DEFAULT 'new',
            created_at TEXT NOT NULL,

            -- Phase 0: expanded quote qualification fields
            facility_type TEXT,
            glass_type TEXT,
            lighting_type TEXT,
            build_context TEXT,
            country TEXT,
            timeline TEXT,
            location_status TEXT,
            financing_status TEXT,
            wants_financing_help INTEGER DEFAULT 0,
            decision_process TEXT,
            previous_supplier_contact TEXT,
            services_needed TEXT,
            additional_info TEXT,
            contact_name TEXT,
            contact_email TEXT,
            contact_phone TEXT,
            contact_company TEXT,
            stakeholder_type TEXT,
            heat_score TEXT DEFAULT 'cool',
            verified_at TEXT,

            -- Phase 1: credit cost and unlock tracking
            credit_cost INTEGER,
            unlock_count INTEGER NOT NULL DEFAULT 0
        )
    """)
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_leads_status ON lead_requests(status)"
    )
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_leads_heat ON lead_requests(heat_score)"
    )

    # Suppliers directory
    conn.execute("""
        CREATE TABLE IF NOT EXISTS suppliers (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name TEXT NOT NULL,
            slug TEXT UNIQUE NOT NULL,
            country_code TEXT NOT NULL,
            city TEXT,
            region TEXT NOT NULL,
            website TEXT,
            description TEXT,
            category TEXT NOT NULL,
            contact TEXT,
            claimed_at TEXT,
            claimed_by INTEGER REFERENCES users(id),
            created_at TEXT NOT NULL DEFAULT (datetime('now')),
            tier TEXT NOT NULL DEFAULT 'free',
            logo_url TEXT,
            is_verified INTEGER NOT NULL DEFAULT 0,
            highlight INTEGER NOT NULL DEFAULT 0,
            sticky_until TEXT,
            sticky_country TEXT,

            -- Phase 1: expanded supplier profile and credits
            service_categories TEXT,
            service_area TEXT,
            years_in_business INTEGER,
            project_count INTEGER,
            short_description TEXT,
            long_description TEXT,
            contact_name TEXT,
            contact_email TEXT,
            contact_phone TEXT,
            credit_balance INTEGER NOT NULL DEFAULT 0,
            monthly_credits INTEGER NOT NULL DEFAULT 0,
            last_credit_refill TEXT,

            -- Phase 2: editable profile fields
            logo_file TEXT,
            tagline TEXT,

            -- Phase 3: Basic tier fields
            services_offered TEXT,
            contact_role TEXT,
            linkedin_url TEXT,
            instagram_url TEXT,
            youtube_url TEXT,

            -- Phase 4: Directory card cover image
            cover_image TEXT
        )
    """)
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_suppliers_country ON suppliers(country_code)"
    )
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_suppliers_category ON suppliers(category)"
    )
    conn.execute("CREATE INDEX IF NOT EXISTS idx_suppliers_slug ON suppliers(slug)")

    # FTS5 full-text search for suppliers
    conn.execute("""
        CREATE VIRTUAL TABLE IF NOT EXISTS suppliers_fts USING fts5(
            name, description, city, country_code, category,
            content='suppliers', content_rowid='id'
        )
    """)

    # Keep FTS in sync with suppliers table
    conn.execute("""
        CREATE TRIGGER IF NOT EXISTS suppliers_ai AFTER INSERT ON suppliers BEGIN
            INSERT INTO suppliers_fts(rowid, name, description, city, country_code, category)
            VALUES (new.id, new.name, new.description, new.city, new.country_code, new.category);
        END
    """)
    conn.execute("""
        CREATE TRIGGER IF NOT EXISTS suppliers_ad AFTER DELETE ON suppliers BEGIN
            INSERT INTO suppliers_fts(suppliers_fts, rowid, name, description, city, country_code, category)
            VALUES ('delete', old.id, old.name, old.description, old.city, old.country_code, old.category);
        END
    """)
    conn.execute("""
        CREATE TRIGGER IF NOT EXISTS suppliers_au AFTER UPDATE ON suppliers BEGIN
            INSERT INTO suppliers_fts(suppliers_fts, rowid, name, description, city, country_code, category)
            VALUES ('delete', old.id, old.name, old.description, old.city, old.country_code, old.category);
            INSERT INTO suppliers_fts(rowid, name, description, city, country_code, category)
            VALUES (new.id, new.name, new.description, new.city, new.country_code, new.category);
        END
    """)

    # Credit ledger
    conn.execute("""
        CREATE TABLE IF NOT EXISTS credit_ledger (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            supplier_id INTEGER NOT NULL REFERENCES suppliers(id),
            delta INTEGER NOT NULL,
            balance_after INTEGER NOT NULL,
            event_type TEXT NOT NULL,
            reference_id INTEGER,
            note TEXT,
            created_at TEXT NOT NULL DEFAULT (datetime('now'))
        )
    """)
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_credit_ledger_supplier ON credit_ledger(supplier_id)"
    )

    # Lead forwards
    conn.execute("""
        CREATE TABLE IF NOT EXISTS lead_forwards (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            lead_id INTEGER NOT NULL REFERENCES lead_requests(id),
            supplier_id INTEGER NOT NULL REFERENCES suppliers(id),
            credit_cost INTEGER NOT NULL,
            status TEXT NOT NULL DEFAULT 'sent',
            email_sent_at TEXT,
            created_at TEXT NOT NULL DEFAULT (datetime('now')),
            UNIQUE(lead_id, supplier_id)
        )
    """)
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_lead_forwards_lead ON lead_forwards(lead_id)"
    )
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_lead_forwards_supplier ON lead_forwards(supplier_id)"
    )

    # Supplier enquiries (Basic+ listing contact form)
    conn.execute("""
        CREATE TABLE IF NOT EXISTS supplier_enquiries (
            id            INTEGER PRIMARY KEY AUTOINCREMENT,
            supplier_id   INTEGER NOT NULL REFERENCES suppliers(id),
            contact_name  TEXT NOT NULL,
            contact_email TEXT NOT NULL,
            message       TEXT NOT NULL,
            status        TEXT NOT NULL DEFAULT 'new',
            created_at    TEXT NOT NULL DEFAULT (datetime('now'))
        )
    """)
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_supplier_enquiries_supplier"
        " ON supplier_enquiries(supplier_id)"
    )
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_supplier_enquiries_email"
        " ON supplier_enquiries(contact_email, created_at)"
    )

    # Supplier boost subscriptions/purchases
    conn.execute("""
        CREATE TABLE IF NOT EXISTS supplier_boosts (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            supplier_id INTEGER NOT NULL REFERENCES suppliers(id),
            boost_type TEXT NOT NULL,
            paddle_subscription_id TEXT,
            status TEXT NOT NULL DEFAULT 'active',
            starts_at TEXT NOT NULL,
            expires_at TEXT,
            metadata TEXT,
            created_at TEXT NOT NULL DEFAULT (datetime('now'))
        )
    """)
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_supplier_boosts_supplier ON supplier_boosts(supplier_id)"
    )

    # Paddle products
    conn.execute("""
        CREATE TABLE IF NOT EXISTS paddle_products (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            key TEXT NOT NULL UNIQUE,
            paddle_product_id TEXT NOT NULL,
            paddle_price_id TEXT NOT NULL,
            name TEXT NOT NULL,
            price_cents INTEGER NOT NULL,
            currency TEXT NOT NULL DEFAULT 'EUR',
            billing_type TEXT NOT NULL,
            created_at TEXT NOT NULL DEFAULT (datetime('now'))
        )
    """)

    # Business plan PDF exports
    conn.execute("""
        CREATE TABLE IF NOT EXISTS business_plan_exports (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            user_id INTEGER NOT NULL REFERENCES users(id),
            scenario_id INTEGER NOT NULL REFERENCES scenarios(id),
            paddle_transaction_id TEXT,
            language TEXT NOT NULL DEFAULT 'en',
            file_path TEXT,
            status TEXT NOT NULL DEFAULT 'pending',
            created_at TEXT NOT NULL DEFAULT (datetime('now')),
            completed_at TEXT
        )
    """)
    conn.execute("CREATE INDEX IF NOT EXISTS idx_bpe_user ON business_plan_exports(user_id)")
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_bpe_scenario ON business_plan_exports(scenario_id)"
    )

    # In-app feedback
    conn.execute("""
        CREATE TABLE IF NOT EXISTS feedback (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            user_id INTEGER REFERENCES users(id),
            page_url TEXT,
            message TEXT NOT NULL,
            is_read INTEGER NOT NULL DEFAULT 0,
            created_at TEXT NOT NULL DEFAULT (datetime('now'))
        )
    """)

    # ==========================================================================
    # Content / Programmatic SEO
    # ==========================================================================

    # Published scenarios
    conn.execute("""
        CREATE TABLE IF NOT EXISTS published_scenarios (
            id           INTEGER PRIMARY KEY AUTOINCREMENT,
            slug         TEXT UNIQUE NOT NULL,
            title        TEXT NOT NULL,
            subtitle     TEXT,
            location     TEXT NOT NULL,
            country      TEXT NOT NULL,
            venue_type   TEXT NOT NULL DEFAULT 'indoor',
            ownership    TEXT NOT NULL DEFAULT 'rent',
            court_config TEXT NOT NULL,
            state_json   TEXT NOT NULL,
            calc_json    TEXT NOT NULL,
            template_data_id INTEGER REFERENCES template_data(id),
            created_at   TEXT NOT NULL DEFAULT (datetime('now')),
            updated_at   TEXT
        )
    """)
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_pub_scenarios_slug ON published_scenarios(slug)"
    )

    # Article templates
    conn.execute("""
        CREATE TABLE IF NOT EXISTS article_templates (
            id                       INTEGER PRIMARY KEY AUTOINCREMENT,
            name                     TEXT NOT NULL,
            slug                     TEXT UNIQUE NOT NULL,
            content_type             TEXT NOT NULL DEFAULT 'calculator',
            input_schema             TEXT NOT NULL,
            url_pattern              TEXT NOT NULL,
            title_pattern            TEXT NOT NULL,
            meta_description_pattern TEXT,
            body_template            TEXT NOT NULL,
            created_at               TEXT NOT NULL DEFAULT (datetime('now')),
            updated_at               TEXT
        )
    """)
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_article_templates_slug ON article_templates(slug)"
    )

    # Template data
    conn.execute("""
        CREATE TABLE IF NOT EXISTS template_data (
            id          INTEGER PRIMARY KEY AUTOINCREMENT,
            template_id INTEGER NOT NULL REFERENCES article_templates(id),
            data_json   TEXT NOT NULL,
            scenario_id INTEGER REFERENCES published_scenarios(id),
            article_id  INTEGER REFERENCES articles(id),
            created_at  TEXT NOT NULL DEFAULT (datetime('now')),
            updated_at  TEXT
        )
    """)
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_template_data_template ON template_data(template_id)"
    )

    # Articles
    conn.execute("""
        CREATE TABLE IF NOT EXISTS articles (
            id               INTEGER PRIMARY KEY AUTOINCREMENT,
            url_path         TEXT UNIQUE NOT NULL,
            slug             TEXT UNIQUE NOT NULL,
            title            TEXT NOT NULL,
            meta_description TEXT,
            country          TEXT,
            region           TEXT,
            og_image_url     TEXT,
            status           TEXT NOT NULL DEFAULT 'draft',
            published_at     TEXT,
            template_data_id INTEGER REFERENCES template_data(id),
            created_at       TEXT NOT NULL DEFAULT (datetime('now')),
            updated_at       TEXT
        )
    """)
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_articles_url_path ON articles(url_path)"
    )
    conn.execute("CREATE INDEX IF NOT EXISTS idx_articles_slug ON articles(slug)")
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_articles_status ON articles(status, published_at)"
    )

    # FTS5 full-text search for articles
    conn.execute("""
        CREATE VIRTUAL TABLE IF NOT EXISTS articles_fts USING fts5(
            title, meta_description, country, region,
            content='articles', content_rowid='id'
        )
    """)

    # Keep FTS in sync with articles table
    conn.execute("""
        CREATE TRIGGER IF NOT EXISTS articles_ai AFTER INSERT ON articles BEGIN
            INSERT INTO articles_fts(rowid, title, meta_description, country, region)
            VALUES (new.id, new.title, new.meta_description, new.country, new.region);
        END
    """)
    conn.execute("""
        CREATE TRIGGER IF NOT EXISTS articles_ad AFTER DELETE ON articles BEGIN
            INSERT INTO articles_fts(articles_fts, rowid, title, meta_description, country, region)
            VALUES ('delete', old.id, old.title, old.meta_description, old.country, old.region);
        END
    """)
    conn.execute("""
        CREATE TRIGGER IF NOT EXISTS articles_au AFTER UPDATE ON articles BEGIN
            INSERT INTO articles_fts(articles_fts, rowid, title, meta_description, country, region)
            VALUES ('delete', old.id, old.title, old.meta_description, old.country, old.region);
            INSERT INTO articles_fts(rowid, title, meta_description, country, region)
            VALUES (new.id, new.title, new.meta_description, new.country, new.region);
        END
    """)
