"""Phase v2.0.4-E - Year Lock and Backup Export

Revision ID: 20260619_phase_204e_year_lock_backup
Revises: 20260618_phase_204d_billing_fy
Create Date: 2026-06-19
"""
from __future__ import annotations

from alembic import op
import sqlalchemy as sa

revision = "20260619_phase_204e_year_lock_backup"
down_revision = "20260618_phase_204d_billing_fy"
branch_labels = None
depends_on = None


def upgrade() -> None:
    op.create_table(
        "year_backup_exports",
        sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True),
        sa.Column("tenant_id", sa.Integer(), nullable=False),
        sa.Column("financial_year_id", sa.Integer(), nullable=False),
        sa.Column("year_code", sa.String(length=9), nullable=False),
        sa.Column("assessment_year", sa.String(length=9), nullable=True),
        sa.Column("export_status", sa.String(length=30), nullable=False, server_default="completed"),
        sa.Column("export_file_path", sa.String(length=1000), nullable=False),
        sa.Column("file_size_bytes", sa.Integer(), nullable=False, server_default="0"),
        sa.Column("manifest_json", sa.Text(), nullable=True),
        sa.Column("generated_by_user_id", sa.Integer(), nullable=True),
        sa.Column("generated_at_utc", sa.DateTime(timezone=True), nullable=False, server_default=sa.text("CURRENT_TIMESTAMP")),
        sa.ForeignKeyConstraint(["tenant_id"], ["tenants.id"], ondelete="CASCADE"),
        sa.ForeignKeyConstraint(["financial_year_id"], ["financial_years.id"], ondelete="CASCADE"),
        sa.ForeignKeyConstraint(["generated_by_user_id"], ["users.id"], ondelete="SET NULL"),
    )
    op.create_index("ix_year_backup_exports_tenant_id", "year_backup_exports", ["tenant_id"])
    op.create_index("ix_year_backup_exports_financial_year_id", "year_backup_exports", ["financial_year_id"])
    op.create_index("ix_year_backup_exports_year_code", "year_backup_exports", ["year_code"])
    op.create_index("ix_year_backup_exports_assessment_year", "year_backup_exports", ["assessment_year"])
    op.create_index("ix_year_backup_exports_export_status", "year_backup_exports", ["export_status"])
    op.create_index("ix_year_backup_exports_generated_by_user_id", "year_backup_exports", ["generated_by_user_id"])


def downgrade() -> None:
    op.drop_index("ix_year_backup_exports_generated_by_user_id", table_name="year_backup_exports")
    op.drop_index("ix_year_backup_exports_export_status", table_name="year_backup_exports")
    op.drop_index("ix_year_backup_exports_assessment_year", table_name="year_backup_exports")
    op.drop_index("ix_year_backup_exports_year_code", table_name="year_backup_exports")
    op.drop_index("ix_year_backup_exports_financial_year_id", table_name="year_backup_exports")
    op.drop_index("ix_year_backup_exports_tenant_id", table_name="year_backup_exports")
    op.drop_table("year_backup_exports")
