"""periodic reports

Revision ID: 0019_periodic_reports
Revises: 0018_ai_cost_tracking
Create Date: 2026-07-31 00:00:00.000000
"""

from __future__ import annotations

from alembic import op
import sqlalchemy as sa

revision = "0019_periodic_reports"
down_revision = "0018_ai_cost_tracking"
branch_labels = None
depends_on = None


def upgrade() -> None:
    op.create_table(
        "sys_periodic_report",
        sa.Column("id", sa.BigInteger().with_variant(sa.Integer(), "sqlite"), primary_key=True, autoincrement=True),
        sa.Column("user_id", sa.BigInteger().with_variant(sa.Integer(), "sqlite"), nullable=False),
        sa.Column("report_type", sa.String(length=30), nullable=False),
        sa.Column("period_start", sa.DateTime(), nullable=False),
        sa.Column("period_end", sa.DateTime(), nullable=False),
        sa.Column("title", sa.String(length=160), nullable=False),
        # MySQL 8.4 rejects literal defaults on TEXT columns. The ORM already
        # supplies an empty string while a report job is pending.
        sa.Column("content", sa.Text(), nullable=False),
        sa.Column("source_summary_ids", sa.Text(), nullable=True),
        sa.Column("source_topic_ids", sa.Text(), nullable=True),
        sa.Column("model_name", sa.String(length=100), nullable=True),
        sa.Column("status", sa.String(length=20), nullable=False, server_default="success"),
        sa.Column("error_message", sa.Text(), nullable=True),
        sa.Column("generated_by", sa.String(length=30), nullable=False, server_default="manual"),
        sa.Column("generated_at", sa.DateTime(), nullable=False, server_default=sa.func.now()),
        sa.Column("created_at", sa.DateTime(), nullable=False, server_default=sa.func.now()),
        sa.Column("updated_at", sa.DateTime(), nullable=False, server_default=sa.func.now()),
        sa.ForeignKeyConstraint(["user_id"], ["sys_user.id"]),
        sa.UniqueConstraint("user_id", "report_type", "period_start", "period_end", name="uq_sys_periodic_report_period"),
    )
    op.create_index("ix_sys_periodic_report_user_id", "sys_periodic_report", ["user_id"])
    op.create_index("ix_sys_periodic_report_status", "sys_periodic_report", ["status"])
    op.create_index("ix_sys_periodic_report_user_type_created", "sys_periodic_report", ["user_id", "report_type", "created_at"])
    op.create_index("ix_sys_periodic_report_status_created", "sys_periodic_report", ["status", "created_at"])


def downgrade() -> None:
    op.drop_index("ix_sys_periodic_report_status_created", table_name="sys_periodic_report")
    op.drop_index("ix_sys_periodic_report_user_type_created", table_name="sys_periodic_report")
    op.drop_index("ix_sys_periodic_report_status", table_name="sys_periodic_report")
    op.drop_index("ix_sys_periodic_report_user_id", table_name="sys_periodic_report")
    op.drop_table("sys_periodic_report")
