"""Add blinks table for persistent rids

Revision ID: 36cdd078f890
Revises: 48dd68d06c60
Create Date: 2024-11-30 21:00:23.413029

"""

from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision: str = "36cdd078f890"
down_revision: Union[str, None] = "48dd68d06c60"
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! ###
    # check if table exists
    conn = op.get_bind()
    inspector = sa.inspect(conn)
    tables = inspector.get_table_names()
    if "blinks" not in tables:
        op.create_table(
            "blinks",
            sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
            sa.Column("rid", sa.String(length=64), nullable=False),
            sa.Column("entity", sa.String(length=64), nullable=True),
            sa.Column("user", sa.String(length=64), nullable=False),
            sa.Column("source", sa.String(length=64), nullable=True),
            sa.Column("rule", sa.String(length=4096), nullable=False),
            sa.Column(
                "status",
                sa.Enum(
                    "UNLINKED",
                    "AUTOMATIC",
                    "SOURCE",
                    "MANUAL",
                    "MHK",
                    "N",
                    "INVALID",
                    name="linkstatus",
                ),
                nullable=False,
            ),
            sa.Column("aregister", sa.String(length=64), nullable=True),
            sa.ForeignKeyConstraint(["rid"], ["rentities.id"], ondelete="CASCADE"),
            sa.PrimaryKeyConstraint("id"),
        )
        op.create_index(op.f("ix_blinks_entity"), "blinks", ["entity"], unique=False)
        op.create_index(op.f("ix_blinks_rid"), "blinks", ["rid"], unique=False)
        op.create_index(op.f("ix_blinks_source"), "blinks", ["source"], unique=False)

    with op.batch_alter_table("links") as batch_op:
        try:
            batch_op.drop_constraint(None, type_="foreignkey")
        except Exception as e:
            print(f"Caught Error dropping constraint: {e}")
        fks = inspector.get_foreign_keys(table_name='links')
        for fk in fks:
            if fk['referred_table'] == 'entities':
                try:
                    batch_op.drop_constraint(fk['name'], type_="foreignkey")
                except Exception as e:
                    print(f"Caught Error dropping constraint: {e}")
        batch_op.create_foreign_key(None, "entities", ["entity"], ["id"])
    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    # this is a workaround for sqlite lack of drop_constrant support
    with op.batch_alter_table("links") as batch_op:
        # cant make the drop_constraint work
        # batch_op.drop(None, type_="foreignkey")
        batch_op.create_foreign_key(
            None,
            referent_table="entities",
            local_cols=["entity"],
            remote_cols=["id"],
            ondelete="SET NULL"
        )

    op.drop_index(op.f("ix_blinks_source"), table_name="blinks")
    op.drop_index(op.f("ix_blinks_rid"), table_name="blinks")
    op.drop_index(op.f("ix_blinks_entity"), table_name="blinks")
    op.drop_table("blinks")
    # ### end Alembic commands ###
