"""Create custom_reports table for saved custom report configs.

Revision ID: 029_custom_reports
Revises: 028_dept_report_idx
Create Date: 2026-08-15
"""

from typing import Sequence, Union

import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import mysql

revision: str = "029_custom_reports"
down_revision: Union[str, None] = "028_dept_report_idx"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    conn = op.get_bind()
    inspector = sa.inspect(conn)
    if "custom_reports" not in inspector.get_table_names():
        op.create_table(
            "custom_reports",
            sa.Column("id", sa.String(length=36), primary_key=True),
            sa.Column("company_id", sa.String(length=36), nullable=False),
            sa.Column("name", sa.String(length=200), nullable=False),
            sa.Column("module", sa.String(length=40), nullable=False),
            sa.Column("description", sa.String(length=500), nullable=True),
            sa.Column("configuration", mysql.JSON(), nullable=False),
            sa.Column("is_template", sa.Boolean(), nullable=False, server_default=sa.text("0")),
            sa.Column("created_by", sa.String(length=36), nullable=True),
            sa.Column("created_at", sa.DateTime(), nullable=False),
            sa.Column("updated_at", sa.DateTime(), nullable=False),
            sa.ForeignKeyConstraint(
                ["company_id"], ["companies.id"], ondelete="CASCADE"
            ),
            sa.UniqueConstraint("company_id", "name", name="uq_custom_reports_company_name"),
        )
        op.create_index("ix_custom_reports_company_id", "custom_reports", ["company_id"])
        op.create_index("ix_custom_reports_module", "custom_reports", ["module"])
        op.create_index("ix_custom_reports_updated_at", "custom_reports", ["updated_at"])


def downgrade() -> None:
    conn = op.get_bind()
    inspector = sa.inspect(conn)
    if "custom_reports" in inspector.get_table_names():
        op.drop_index("ix_custom_reports_updated_at", table_name="custom_reports")
        op.drop_index("ix_custom_reports_module", table_name="custom_reports")
        op.drop_index("ix_custom_reports_company_id", table_name="custom_reports")
        op.drop_table("custom_reports")
