"""P1-1: 时间列改 TIMESTAMPTZ (created_at / updated_at)

把 16 张表的 created_at/updated_at 由 TIMESTAMP WITHOUT TIME ZONE
改为 TIMESTAMPTZ。既有数据按服务器本地时存的裸时间一律解释为 UTC：
`ALTER ... TYPE TIMESTAMPTZ USING <col> AT TIME ZONE 'UTC'`
（autogenerate 不会生成 USING 子句，手写）。downgrade 反向，
TIMESTAMPTZ → naive 时丢弃时区（按 UTC 墙钟取值）。

Revision ID: b1a2c3d4e5f6
Revises: ad2c4c663daf
Create Date: 2026-06-21 00:00:00.000000
"""

from __future__ import annotations

from collections.abc import Sequence

from alembic import op

revision: str = "b1a2c3d4e5f6"
down_revision: str | None = "ad2c4c663daf"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None

# (table, column) — 所有时间列。
_CREATED_AT_TABLES: tuple[str, ...] = (
    "users",
    "projects",
    "skills",
    "chapter_digests",
    "chapter_reviews",
    "chapters",
    "characters",
    "jobs",
    "provider_credentials",
    "rules",
    "style_fingerprint",
    "usage_ledger",
    "world_entities",
    "chapter_injection",
)
_UPDATED_AT_TABLES: tuple[str, ...] = (
    "projects",
    "foreshadow",
    "jobs",
    "chapter_injection",
)


def _columns() -> list[tuple[str, str]]:
    cols = [(t, "created_at") for t in _CREATED_AT_TABLES]
    cols += [(t, "updated_at") for t in _UPDATED_AT_TABLES]
    return cols


def upgrade() -> None:
    for table, column in _columns():
        op.execute(
            f"ALTER TABLE {table} "
            f"ALTER COLUMN {column} TYPE TIMESTAMP WITH TIME ZONE "
            f"USING {column} AT TIME ZONE 'UTC'"
        )


def downgrade() -> None:
    for table, column in _columns():
        op.execute(
            f"ALTER TABLE {table} "
            f"ALTER COLUMN {column} TYPE TIMESTAMP WITHOUT TIME ZONE "
            f"USING {column} AT TIME ZONE 'UTC'"
        )
