"""add_session_id_to_resume

Revision ID: 4e19b8fe4a88
Revises: ae966b3e742e
Create Date: 2025-08-30 20:38:36.867781

"""

from collections.abc import Sequence

import sqlalchemy as sa
from alembic import op

# revision identifiers, used by Alembic.
revision: str = "4e19b8fe4a88"
down_revision: str | Sequence[str] | None = "ae966b3e742e"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None


def upgrade() -> None:
    """Upgrade schema."""
    # ### commands auto generated by Alembic - please adjust! ###
    # Сначала добавляем колонку как nullable
    op.add_column("resume", sa.Column("session_id", sa.Integer(), nullable=True))

    # Создаем временную сессию для существующих резюме (если есть)
    op.execute("""
        INSERT INTO session (session_id, is_active, expires_at, last_activity, created_at, updated_at)
        SELECT 
            'legacy-' || CAST(EXTRACT(epoch FROM NOW()) AS TEXT),
            true,
            NOW() + INTERVAL '30 days',
            NOW(),
            NOW(),
            NOW()
        WHERE NOT EXISTS (SELECT 1 FROM session LIMIT 1)
    """)

    # Обновляем существующие резюме, привязывая их к первой сессии
    op.execute("""
        UPDATE resume 
        SET session_id = (SELECT id FROM session ORDER BY id LIMIT 1)
        WHERE session_id IS NULL
    """)

    # Теперь делаем колонку NOT NULL
    op.alter_column("resume", "session_id", nullable=False)

    op.create_foreign_key(None, "resume", "session", ["session_id"], ["id"])
    # ### end Alembic commands ###


def downgrade() -> None:
    """Downgrade schema."""
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint(None, "resume", type_="foreignkey")
    op.drop_column("resume", "session_id")
    # ### end Alembic commands ###
