"""Add soft delete to user agents

Revision ID: 9f61865b8ba8
Revises: 2e2f1b18e835
Create Date: 2025-08-10 22:22:28.432623

"""

from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision: str = "9f61865b8ba8"
down_revision: Union[str, None] = "2e2f1b18e835"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    # Add column as nullable first with server default
    op.add_column(
        "user_agents",
        sa.Column(
            "is_deleted", sa.Boolean(), server_default=sa.text("FALSE"), nullable=True
        ),
    )

    # Set default value for existing rows (in case any are NULL)
    op.execute("UPDATE user_agents SET is_deleted = FALSE WHERE is_deleted IS NULL")

    # Now make the column NOT NULL
    op.alter_column(
        "user_agents", "is_deleted", nullable=False, server_default=sa.text("FALSE")
    )

    op.drop_constraint(
        op.f("uq_user_agents_user_id_name"), "user_agents", type_="unique"
    )
    op.create_index(
        "uq_user_agents_user_id_name",
        "user_agents",
        ["user_id", "name"],
        unique=True,
        postgresql_where=sa.text("is_deleted = FALSE"),
    )
    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_index(
        "uq_user_agents_user_id_name",
        table_name="user_agents",
        postgresql_where=sa.text("is_deleted = FALSE"),
    )
    op.create_unique_constraint(
        op.f("uq_user_agents_user_id_name"),
        "user_agents",
        ["user_id", "name"],
        postgresql_nulls_not_distinct=False,
    )
    op.drop_column("user_agents", "is_deleted")
    # ### end Alembic commands ###
