"""
Add Basic tier supplier fields and supplier_enquiries table.
New columns on suppliers: services_offered, contact_role, linkedin_url,
instagram_url, youtube_url.
New table: supplier_enquiries.
"""


def _column_names(conn, table):
    return [r[1] for r in conn.execute(f"PRAGMA table_info({table})").fetchall()]


def up(conn):
    cols = _column_names(conn, "suppliers")

    for col, defn in [
        ("services_offered", "TEXT"),
        ("contact_role",     "TEXT"),
        ("linkedin_url",     "TEXT"),
        ("instagram_url",    "TEXT"),
        ("youtube_url",      "TEXT"),
    ]:
        if col not in cols:
            conn.execute(f"ALTER TABLE suppliers ADD COLUMN {col} {defn}")

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