"""Phase 2: paddle_products, business_plan_exports, feedback tables; supplier profile columns."""


def up(conn):
    # -- paddle_products: store Paddle product/price IDs in DB --
    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_exports: track PDF purchases and generation --
    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)"
    )

    # -- feedback: in-app feedback submissions --
    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'))
        )
    """)

    # -- Column additions to suppliers --
    sup_cols = {r[1] for r in conn.execute("PRAGMA table_info(suppliers)").fetchall()}
    new_sup_cols = {
        "logo_file": "TEXT",
        "tagline": "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}")
