"""Add leads table for sales lead tracking.

Revision ID: 0012
Revises: 0011
"""

from typing import Sequence, Union

import sqlalchemy as sa
from alembic import op

revision: str = "0012"
down_revision: Union[str, None] = "0011"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    conn = op.get_bind()

    conn.execute(
        sa.text("""
            CREATE TABLE IF NOT EXISTS leads (
                id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
                project_id TEXT NOT NULL REFERENCES projects(id),
                name TEXT NOT NULL,
                email TEXT NOT NULL,
                contact_phone TEXT,
                company TEXT,
                source TEXT,
                status TEXT NOT NULL DEFAULT 'new'
                    CHECK(status IN (
                        'new', 'researching', 'qualified', 'outreach_ready',
                        'contacted', 'responded', 'converted', 'disqualified'
                    )),
                notes TEXT,
                metadata JSONB,
                created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
                CONSTRAINT uq_leads_project_email UNIQUE (project_id, email)
            )
        """)
    )

    conn.execute(
        sa.text(
            "CREATE INDEX IF NOT EXISTS idx_leads_project_id ON leads(project_id)"
        )
    )
    conn.execute(
        sa.text("CREATE INDEX IF NOT EXISTS idx_leads_status ON leads(status)")
    )
    conn.execute(
        sa.text(
            "CREATE INDEX IF NOT EXISTS idx_leads_created_at ON leads(created_at)"
        )
    )

    # Trigger to auto-update updated_at on row modification
    conn.execute(
        sa.text("""
            CREATE OR REPLACE FUNCTION set_updated_at()
            RETURNS TRIGGER AS $$
            BEGIN
                NEW.updated_at = CURRENT_TIMESTAMP;
                RETURN NEW;
            END;
            $$ LANGUAGE plpgsql
        """)
    )
    conn.execute(
        sa.text("""
            CREATE TRIGGER leads_set_updated_at
            BEFORE UPDATE ON leads
            FOR EACH ROW EXECUTE FUNCTION set_updated_at()
        """)
    )


def downgrade() -> None:
    conn = op.get_bind()
    conn.execute(sa.text("DROP TABLE IF EXISTS leads"))
    # Note: set_updated_at() function is intentionally left — it may be used by future tables
