"""add feedback username snapshot

Revision ID: 20260730_07
Revises: 20260730_06
Create Date: 2026-07-30
"""
from __future__ import annotations

from collections.abc import Sequence

import sqlalchemy as sa
from alembic import op

revision: str = "20260730_07"
down_revision: str | None = "20260730_06"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None


def upgrade() -> None:
    op.add_column(
        "demand_feedback",
        sa.Column(
            "feedback_username_snapshot",
            sa.String(length=64),
            nullable=False,
            server_default="",
            comment="反馈人登录账号快照",
        ),
    )
    op.execute(
        sa.text(
            """
            UPDATE demand_feedback AS feedback
            JOIN auth_user AS user_account
              ON user_account.id = feedback.feedback_user_id
            SET feedback.feedback_username_snapshot = user_account.username
            WHERE feedback.feedback_username_snapshot = ''
            """
        )
    )
    op.alter_column(
        "demand_feedback",
        "feedback_username_snapshot",
        existing_type=sa.String(length=64),
        server_default=None,
    )


def downgrade() -> None:
    op.drop_column("demand_feedback", "feedback_username_snapshot")
