"""pending_imports — the two-step import staging table (M4; ADR #041
two-step flow; imports.md B37–B39 shape, rebuild edition).

Mirrors the legacy table: jsonb parsed-entries payload, uploader
attribution (effective user — ADR #033 carry-over), 24h expiry. Two
deliberate deltas from the legacy shape (ADR #005):

  - `expires_at` is ENFORCED (T-IMP-031): expired rows are purged on
    upload and treated as not-found on read — the legacy app's "24h"
    was UI copy with no teeth.
  - `tenant_id` carries NO foreign key: the nightly rebuild-from-legacy
    transforms TRUNCATE/DELETE the entity tables (tenants included),
    and an FK from this table would break that pipeline (staging rows
    are ephemeral by design; a stale tenant_id after a rehearsal
    rebuild simply never matches the active tenant again — equivalent
    to expiry).

parse_errors/parse_warnings/total_rows persist the parse report so the
resolver page can surface skipped rows (T-IMP-011 — the legacy app
swallowed them; documented wart #1 fixed).

Revision ID: 0004
Revises: 0003
Create Date: 2026-07-08
"""

from collections.abc import Sequence

import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

from alembic import op

revision: str = "0004"
down_revision: str | None = "0003"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None


def upgrade() -> None:
    op.create_table(
        "pending_imports",
        sa.Column(
            "id",
            postgresql.UUID(as_uuid=True),
            primary_key=True,
            server_default=sa.text("gen_random_uuid()"),
        ),
        # deliberately NOT a foreign key — see module docstring
        sa.Column("tenant_id", postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column(
            "uploaded_by",
            postgresql.UUID(as_uuid=True),
            sa.ForeignKey("users.id", ondelete="CASCADE"),
            nullable=False,
        ),
        sa.Column(
            "uploaded_at",
            sa.DateTime(timezone=True),
            nullable=False,
            server_default=sa.text("now()"),
        ),
        sa.Column(
            "expires_at",
            sa.DateTime(timezone=True),
            nullable=False,
            server_default=sa.text("now() + interval '24 hours'"),
        ),
        sa.Column("filename", sa.Text(), nullable=True),
        sa.Column("batch_name", sa.Text(), nullable=True),
        sa.Column("notes", sa.Text(), nullable=True),
        # the importer only speaks Clockify (judgment #8); manual entry
        # never stages
        sa.Column(
            "source", sa.Text(), nullable=False, server_default=sa.text("'clockify'")
        ),
        # the date format the parser actually used (detected ?? fallback)
        # — provenance only; commit never re-parses
        sa.Column("date_format", sa.Text(), nullable=True),
        sa.Column("parsed_entries", postgresql.JSONB(), nullable=False),
        sa.Column(
            "parse_errors",
            postgresql.JSONB(),
            nullable=False,
            server_default=sa.text("'[]'::jsonb"),
        ),
        sa.Column(
            "parse_warnings",
            postgresql.JSONB(),
            nullable=False,
            server_default=sa.text("'[]'::jsonb"),
        ),
        sa.Column("total_rows", sa.Integer(), nullable=False, server_default=sa.text("0")),
        sa.CheckConstraint("source IN ('clockify')", name="ck_pending_imports_source"),
    )
    op.create_index("ix_pending_imports_uploaded_by", "pending_imports", ["uploaded_by"])
    op.create_index("ix_pending_imports_expires_at", "pending_imports", ["expires_at"])


def downgrade() -> None:
    op.drop_table("pending_imports")
