"""add finalized fields to privacy request

Revision ID: a7065df4dcf1
Revises: 7e9a2b52f498
Create Date: 2025-07-01 14:07:36.779437

"""

import sqlalchemy as sa
from alembic import op

# revision identifiers, used by Alembic.
revision = "a7065df4dcf1"
down_revision = "7e9a2b52f498"
branch_labels = None
depends_on = None


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column(
        "privacyrequest",
        sa.Column("finalized_at", sa.DateTime(timezone=True), nullable=True),
    )
    op.add_column(
        "privacyrequest", sa.Column("finalized_by", sa.String(), nullable=True)
    )
    op.create_foreign_key(
        "privacyrequest_fidesuser_id_fkey",
        "privacyrequest",
        "fidesuser",
        ["finalized_by"],
        ["id"],
        ondelete="SET NULL",
    )
    op.execute(
        "alter type privacyrequeststatus add value 'requires_manual_finalization'"
    )
    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint(
        "privacyrequest_fidesuser_id_fkey", "privacyrequest", type_="foreignkey"
    )
    op.drop_column("privacyrequest", "finalized_by")
    op.drop_column("privacyrequest", "finalized_at")

    op.execute(
        "delete from privacyrequest where status in ('requires_manual_finalization')"
    )

    op.execute("alter type privacyrequeststatus rename to privacyrequeststatus_old")
    op.execute(
        "create type privacyrequeststatus as enum('identity_unverified', 'requires_input', 'pending', 'in_processing', 'complete', 'pending', 'error', 'paused', 'approved', 'denied', 'canceled', 'awaiting_email_send')"
    )
    op.execute(
        (
            "alter table privacyrequest alter column status type privacyrequeststatus using "
            "status::text::privacyrequeststatus"
        )
    )
    op.execute("drop type privacyrequeststatus_old")
    # ### end Alembic commands ###
