"""add upload_status to attachments

Tracks the two-phase upload lifecycle:
  PENDING   - row created, awaiting client's direct upload to MinIO
  CONFIRMED - client finished upload, /confirm endpoint verified head_object
  FAILED    - presign issued but client never completed; swept by cron

Revision ID: 002_add_upload_status
Revises: 001_initial_schema
"""
from alembic import op
import sqlalchemy as sa


revision = "002_add_upload_status"
down_revision = "001_initial_schema"


def upgrade():
    op.add_column(
        "attachments",
        sa.Column(
            "upload_status",
            sa.String(16),
            nullable=False,
            server_default="CONFIRMED",  # existing rows are already confirmed
        ),
    )
    op.create_check_constraint(
        "chk_attachment_upload_status",
        "attachments",
        "upload_status IN ('PENDING','CONFIRMED','FAILED')",
    )
    op.add_column(
        "attachments",
        sa.Column("sha256", sa.String(64), nullable=True),
    )
    # Partial index so the cleanup cron can find stale PENDINGs fast
    op.create_index(
        "idx_attach_pending",
        "attachments",
        ["uploaded_at"],
        postgresql_where=sa.text("upload_status = 'PENDING'"),
    )


def downgrade():
    op.drop_index("idx_attach_pending", table_name="attachments")
    op.drop_column("attachments", "sha256")
    op.drop_constraint("chk_attachment_upload_status", "attachments")
    op.drop_column("attachments", "upload_status")
