"""Add table to store binary data.

Revision ID: 53a0d4789886
Revises: 3715fd158e35
Create Date: 2026-02-23 09:52:42.731689
"""

from typing import Sequence, Union

import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql
from xplan_tools.settings import get_settings

# revision identifiers, used by Alembic.
revision: str = "53a0d4789886"
down_revision: Union[str, Sequence[str], None] = "3715fd158e35"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None

schema = get_settings().db_schema or "public"


def upgrade() -> None:
    """Upgrade schema."""
    op.create_table(
        "docs",
        sa.Column("pk", sa.BigInteger(), sa.Identity(always=True), nullable=False),
        sa.Column(
            "id",
            sa.Uuid(as_uuid=False),
            nullable=False,
        ),
        sa.Column("filename", sa.Text(), nullable=False),
        sa.Column("filetype", sa.Text(), nullable=False),
        sa.Column("filedata", postgresql.BYTEA(), nullable=False),
        sa.ForeignKeyConstraint(
            ["id"],
            [f"{schema}.coretable.id"],
            ondelete="CASCADE",
            initially="DEFERRED",
            deferrable=True,
        ),
        sa.PrimaryKeyConstraint("pk"),
        schema=schema,
    )
    op.create_index(
        op.f("ix_docs_filename"), "docs", ["filename"], schema=schema, unique=True
    )
    op.create_index(op.f("ix_docs_id"), "docs", ["id"], schema=schema)


def downgrade() -> None:
    """Downgrade schema."""
    op.drop_index(op.f("ix_docs_id"), table_name="docs", schema=schema)
    op.drop_index(
        op.f("ix_docs_filename"), table_name="docs", schema=schema, if_exists=True
    )
    op.drop_table("docs", schema=schema)
