"""Add unique constraints

Revision ID: 006b3990db50
Revises: 1ef9c4f3765d
Create Date: 2023-12-13 18:55:52.587360

"""

from collections.abc import Sequence

import sqlalchemy as sa
from alembic import op

# revision identifiers, used by Alembic.
revision: str = "006b3990db50"
down_revision: str | None = "1ef9c4f3765d"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None


def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    conn = op.get_bind()
    inspector = sa.inspect(conn)  # type: ignore
    api_key_constraints = inspector.get_unique_constraints("apikey")
    flow_constraints = inspector.get_unique_constraints("flow")
    user_constraints = inspector.get_unique_constraints("user")
    try:
        if not any(constraint["column_names"] == ["id"] for constraint in api_key_constraints):
            with op.batch_alter_table("apikey", schema=None) as batch_op:
                batch_op.create_unique_constraint("uq_apikey_id", ["id"])
        if not any(constraint["column_names"] == ["id"] for constraint in flow_constraints):
            with op.batch_alter_table("flow", schema=None) as batch_op:
                batch_op.create_unique_constraint("uq_flow_id", ["id"])
        if not any(constraint["column_names"] == ["id"] for constraint in user_constraints):
            with op.batch_alter_table("user", schema=None) as batch_op:
                batch_op.create_unique_constraint("uq_user_id", ["id"])
    except Exception as e:
        print(e)

    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    conn = op.get_bind()
    inspector = sa.inspect(conn)  # type: ignore
    api_key_constraints = inspector.get_unique_constraints("apikey")
    flow_constraints = inspector.get_unique_constraints("flow")
    user_constraints = inspector.get_unique_constraints("user")
    try:
        if any(constraint["name"] == "uq_apikey_id" for constraint in api_key_constraints):
            with op.batch_alter_table("user", schema=None) as batch_op:
                batch_op.drop_constraint("uq_user_id", type_="unique")
        if any(constraint["name"] == "uq_flow_id" for constraint in flow_constraints):
            with op.batch_alter_table("flow", schema=None) as batch_op:
                batch_op.drop_constraint("uq_flow_id", type_="unique")
        if any(constraint["name"] == "uq_user_id" for constraint in user_constraints):
            with op.batch_alter_table("apikey", schema=None) as batch_op:
                batch_op.drop_constraint("uq_apikey_id", type_="unique")
    except Exception as e:
        print(e)
    # ### end Alembic commands ###
