"""fc2d-iii: post_attachment + import_batch.attachments

Revision ID: 0009
Revises: 0008
Create Date: 2026-05-19

Internal forward-correctness migration (big legacy-import migration
stays deferred). No backfill — no attachments exist yet.
"""
from typing import Sequence, Union

import sqlalchemy as sa
from alembic import op

revision: str = "0009"
down_revision: Union[str, None] = "0008"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    op.create_table(
        "post_attachment",
        sa.Column("id", sa.Integer(), primary_key=True),
        sa.Column(
            "post_id", sa.Integer(),
            sa.ForeignKey("post.id", ondelete="SET NULL"), nullable=True,
        ),
        sa.Column(
            "artist_id", sa.Integer(),
            sa.ForeignKey("artist.id", ondelete="SET NULL"), nullable=True,
        ),
        sa.Column("sha256", sa.String(64), nullable=False),
        sa.Column("path", sa.Text(), nullable=False),
        sa.Column("original_filename", sa.Text(), nullable=False),
        sa.Column("ext", sa.String(32), nullable=False),
        sa.Column("mime", sa.String(128), nullable=True),
        sa.Column("size_bytes", sa.BigInteger(), nullable=False),
        sa.Column(
            "captured_at", sa.DateTime(timezone=True),
            server_default=sa.func.now(), nullable=False,
        ),
    )
    op.create_index(
        "ix_post_attachment_sha256", "post_attachment", ["sha256"],
        unique=True,
    )
    op.create_index(
        "ix_post_attachment_post_id", "post_attachment", ["post_id"],
    )
    op.create_index(
        "ix_post_attachment_artist_id", "post_attachment", ["artist_id"],
    )
    op.add_column(
        "import_batch",
        sa.Column(
            "attachments", sa.Integer(), nullable=False,
            server_default="0",
        ),
    )


def downgrade() -> None:
    op.drop_column("import_batch", "attachments")
    op.drop_index("ix_post_attachment_artist_id", table_name="post_attachment")
    op.drop_index("ix_post_attachment_post_id", table_name="post_attachment")
    op.drop_index("ix_post_attachment_sha256", table_name="post_attachment")
    op.drop_table("post_attachment")
