"""Phase v2.0.4-A - Financial Year Master and Active FY Context

Revision ID: 20260617_phase_204a_financial_year
Revises: 20260616_phase_8b_notice_cases
Create Date: 2026-06-17
"""
from __future__ import annotations

from datetime import date, datetime, timezone

from alembic import op
import sqlalchemy as sa

revision = "20260617_phase_204a_financial_year"
down_revision = "20260616_phase_8b_notice_cases"
branch_labels = None
depends_on = None


def upgrade() -> None:
    op.create_table(
        "financial_years",
        sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True),
        sa.Column("tenant_id", sa.Integer(), nullable=False),
        sa.Column("year_code", sa.String(9), nullable=False),
        sa.Column("assessment_year", sa.String(9), nullable=False),
        sa.Column("start_date", sa.Date(), nullable=False),
        sa.Column("end_date", sa.Date(), nullable=False),
        sa.Column("is_current", sa.Boolean(), nullable=False, server_default=sa.false()),
        sa.Column("is_locked", sa.Boolean(), nullable=False, server_default=sa.false()),
        sa.Column("locked_at_utc", sa.DateTime(timezone=True), nullable=True),
        sa.Column("locked_by_user_id", sa.Integer(), nullable=True),
        sa.Column("created_at_utc", sa.DateTime(timezone=True), nullable=False),
        sa.Column("updated_at_utc", sa.DateTime(timezone=True), nullable=False),
        sa.ForeignKeyConstraint(["tenant_id"], ["tenants.id"], name="fk_financial_years_tenant", ondelete="CASCADE"),
        sa.ForeignKeyConstraint(["locked_by_user_id"], ["users.id"], name="fk_financial_years_locked_by", ondelete="SET NULL"),
        sa.UniqueConstraint("tenant_id", "year_code", name="uq_financial_year_tenant_code"),
    )
    op.create_index("ix_financial_years_tenant_id", "financial_years", ["tenant_id"])
    op.create_index("ix_financial_years_year_code", "financial_years", ["year_code"])
    op.create_index("ix_financial_years_assessment_year", "financial_years", ["assessment_year"])
    op.create_index("ix_financial_years_is_current", "financial_years", ["is_current"])
    op.create_index("ix_financial_years_is_locked", "financial_years", ["is_locked"])
    op.create_index("ix_financial_years_locked_by_user_id", "financial_years", ["locked_by_user_id"])

    # Seed the default FY for every existing tenant so the selector works immediately
    # after upgrade. Further years can be created from System Settings.
    conn = op.get_bind()
    tenants = conn.execute(sa.text("SELECT id FROM tenants")).fetchall()
    now = datetime.now(timezone.utc)
    for row in tenants:
        tenant_id = row[0]
        exists = conn.execute(
            sa.text("SELECT id FROM financial_years WHERE tenant_id = :tenant_id AND year_code = :year_code"),
            {"tenant_id": tenant_id, "year_code": "2025-26"},
        ).first()
        if exists:
            continue
        conn.execute(
            sa.text(
                """
                INSERT INTO financial_years
                (tenant_id, year_code, assessment_year, start_date, end_date, is_current, is_locked, created_at_utc, updated_at_utc)
                VALUES
                (:tenant_id, :year_code, :assessment_year, :start_date, :end_date, :is_current, :is_locked, :created_at_utc, :updated_at_utc)
                """
            ),
            {
                "tenant_id": tenant_id,
                "year_code": "2025-26",
                "assessment_year": "2026-27",
                "start_date": date(2025, 4, 1),
                "end_date": date(2026, 3, 31),
                "is_current": True,
                "is_locked": False,
                "created_at_utc": now,
                "updated_at_utc": now,
            },
        )


def downgrade() -> None:
    op.drop_index("ix_financial_years_locked_by_user_id", table_name="financial_years")
    op.drop_index("ix_financial_years_is_locked", table_name="financial_years")
    op.drop_index("ix_financial_years_is_current", table_name="financial_years")
    op.drop_index("ix_financial_years_assessment_year", table_name="financial_years")
    op.drop_index("ix_financial_years_year_code", table_name="financial_years")
    op.drop_index("ix_financial_years_tenant_id", table_name="financial_years")
    op.drop_table("financial_years")
