"""Phase 1: credit ledger, lead forwarding, supplier boosts, expanded supplier/lead columns."""


def up(conn):
    # -- New tables --

    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)")

    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)")

    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,
            created_at TEXT NOT NULL DEFAULT (datetime('now'))
        )
    """)
    conn.execute("CREATE INDEX IF NOT EXISTS idx_supplier_boosts_supplier ON supplier_boosts(supplier_id)")

    # -- Column additions to suppliers --
    sup_cols = {r[1] for r in conn.execute("PRAGMA table_info(suppliers)").fetchall()}
    new_sup_cols = {
        "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",
    }
    for col, typedef in new_sup_cols.items():
        if col not in sup_cols:
            conn.execute(f"ALTER TABLE suppliers ADD COLUMN {col} {typedef}")

    # -- Column additions to lead_requests --
    lead_cols = {r[1] for r in conn.execute("PRAGMA table_info(lead_requests)").fetchall()}
    if "credit_cost" not in lead_cols:
        conn.execute("ALTER TABLE lead_requests ADD COLUMN credit_cost INTEGER")
    if "unlock_count" not in lead_cols:
        conn.execute("ALTER TABLE lead_requests ADD COLUMN unlock_count INTEGER NOT NULL DEFAULT 0")
