"""Add video_consents and consent_audit_log tables for per-video consent management.

Revision ID: 017_add_consent_tables
Revises: 016_add_users_and_invite_codes
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects.postgresql import UUID

revision = "017_add_consent_tables"
down_revision = "016_add_users_and_invite_codes"
branch_labels = None
depends_on = None


def upgrade() -> None:
    # Create video_consents table
    op.create_table(
        "video_consents",
        sa.Column("id", UUID(as_uuid=True), primary_key=True, server_default=sa.func.gen_random_uuid()),
        sa.Column("source_video_id", UUID(as_uuid=True), sa.ForeignKey("source_videos.id", ondelete="CASCADE"), nullable=False),
        sa.Column("creator_id", UUID(as_uuid=True), sa.ForeignKey("creators.id", ondelete="CASCADE"), nullable=False),
        sa.Column("kb_inclusion", sa.Boolean(), nullable=False, server_default="false"),
        sa.Column("training_usage", sa.Boolean(), nullable=False, server_default="false"),
        sa.Column("public_display", sa.Boolean(), nullable=False, server_default="true"),
        sa.Column("updated_by", UUID(as_uuid=True), sa.ForeignKey("users.id", ondelete="RESTRICT"), nullable=False),
        sa.Column("created_at", sa.DateTime(), nullable=False, server_default=sa.func.now()),
        sa.Column("updated_at", sa.DateTime(), nullable=False, server_default=sa.func.now()),
        sa.UniqueConstraint("source_video_id", name="uq_video_consent_video"),
    )

    # Create consent_audit_log table
    op.create_table(
        "consent_audit_log",
        sa.Column("id", UUID(as_uuid=True), primary_key=True, server_default=sa.func.gen_random_uuid()),
        sa.Column("video_consent_id", UUID(as_uuid=True), sa.ForeignKey("video_consents.id", ondelete="CASCADE"), nullable=False),
        sa.Column("version", sa.Integer(), nullable=False),
        sa.Column("field_name", sa.String(50), nullable=False),
        sa.Column("old_value", sa.Boolean(), nullable=True),
        sa.Column("new_value", sa.Boolean(), nullable=False),
        sa.Column("changed_by", UUID(as_uuid=True), sa.ForeignKey("users.id", ondelete="RESTRICT"), nullable=False),
        sa.Column("ip_address", sa.String(45), nullable=True),
        sa.Column("created_at", sa.DateTime(), nullable=False, server_default=sa.func.now()),
    )
    op.create_index("ix_consent_audit_log_video_consent_id", "consent_audit_log", ["video_consent_id"])


def downgrade() -> None:
    op.drop_index("ix_consent_audit_log_video_consent_id", table_name="consent_audit_log")
    op.drop_table("consent_audit_log")
    op.drop_table("video_consents")
