"""proposals: add declined_at, expires_at columns; add status + opportunity indexes

Revision ID: 0040
Revises: 0039
Create Date: 2026-07-01

Changes:
  - proposals: add declined_at (TIMESTAMPTZ NULL)
  - proposals: add expires_at (TIMESTAMPTZ NULL)
  - proposals: add partial index on (tenant_id, status) WHERE deleted_at IS NULL
  - proposals: add partial index on (tenant_id, opportunity_id) WHERE deleted_at IS NULL
"""
from alembic import op
import sqlalchemy as sa

revision = "0040"
down_revision = "0039"
branch_labels = None
depends_on = None


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

    conn.execute(sa.text(
        "ALTER TABLE proposals ADD COLUMN IF NOT EXISTS declined_at TIMESTAMPTZ"
    ))
    conn.execute(sa.text(
        "ALTER TABLE proposals ADD COLUMN IF NOT EXISTS expires_at TIMESTAMPTZ"
    ))

    conn.execute(sa.text("""
        CREATE INDEX IF NOT EXISTS ix_proposals_tenant_status
        ON proposals (tenant_id, status)
        WHERE deleted_at IS NULL
    """))
    conn.execute(sa.text("""
        CREATE INDEX IF NOT EXISTS ix_proposals_tenant_opp
        ON proposals (tenant_id, opportunity_id)
        WHERE deleted_at IS NULL
    """))


def downgrade() -> None:
    conn = op.get_bind()
    conn.execute(sa.text("DROP INDEX IF EXISTS ix_proposals_tenant_opp"))
    conn.execute(sa.text("DROP INDEX IF EXISTS ix_proposals_tenant_status"))
    conn.execute(sa.text("ALTER TABLE proposals DROP COLUMN IF EXISTS expires_at"))
    conn.execute(sa.text("ALTER TABLE proposals DROP COLUMN IF EXISTS declined_at"))
