"""phase-20: 수신 시각(email.received_at) — 목록 최신순 정렬·표시 기준

Revision ID: p20b8c9d0e1f2
Revises: p19a7b8c9d0e1
Create Date: 2026-06-18 00:00:00.000000

"""

from typing import Sequence, Union

import sqlalchemy as sa
from alembic import op

revision: str = "p20b8c9d0e1f2"
down_revision: Union[str, Sequence[str], None] = "p19a7b8c9d0e1"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    op.add_column("email", sa.Column("received_at", sa.DateTime(), nullable=True))
    op.create_index("ix_email_received_at", "email", ["received_at"])
    # 기존 행 백필: ExternalLink.external_updated_at(실제 수신 시각)에서 채운다.
    op.execute(
        """
        UPDATE email SET received_at = (
            SELECT el.external_updated_at FROM external_link el
            WHERE el.entity_id = email.id AND el.entity_type = 'email'
            LIMIT 1
        )
        WHERE received_at IS NULL
        """
    )


def downgrade() -> None:
    op.drop_index("ix_email_received_at", table_name="email")
    op.drop_column("email", "received_at")
