"""upstream action audit logs

Revision ID: 039_upstream_actions
Revises: 038_refunds
Create Date: 2026-06-17
"""
import sqlalchemy as sa
from alembic import op


revision = "039_upstream_actions"
down_revision = "038_refunds"
branch_labels = None
depends_on = None


def _index_names(bind, table_name: str) -> set[str]:
    return {index["name"] for index in sa.inspect(bind).get_indexes(table_name)}


def upgrade() -> None:
    bind = op.get_bind()
    tables = set(sa.inspect(bind).get_table_names())

    if "upstream_action_logs" not in tables:
        op.create_table(
            "upstream_action_logs",
            sa.Column("user_id", sa.BigInteger(), nullable=True),
            sa.Column("order_id", sa.Integer(), nullable=True),
            sa.Column("order_refund_id", sa.Integer(), nullable=True),
            sa.Column("instance_id", sa.Integer(), nullable=True),
            sa.Column("cloud_server_id", sa.Integer(), nullable=True),
            sa.Column("upstream_id", sa.Integer(), nullable=True),
            sa.Column("action_type", sa.String(48), nullable=False, comment="instance_delete / disk_delete / suspend ..."),
            sa.Column("resource_type", sa.String(32), nullable=False, comment="instance / disk / package / bandwidth"),
            sa.Column("resource_id", sa.String(64), nullable=True),
            sa.Column("source", sa.String(32), nullable=False, comment="manual / unsubscribe / lifecycle / renewal"),
            sa.Column(
                "status",
                sa.String(24),
                nullable=False,
                server_default=sa.text("'submitted'"),
                comment="submitted / running / success / failed / no_task",
            ),
            sa.Column("upstream_task_id", sa.Integer(), nullable=True),
            sa.Column("request_method", sa.String(8), nullable=True),
            sa.Column("request_path", sa.String(255), nullable=True),
            sa.Column("request_payload", sa.JSON(), nullable=True),
            sa.Column("response_payload", sa.JSON(), nullable=True),
            sa.Column("task_payload", sa.JSON(), nullable=True),
            sa.Column("error_message", sa.Text(), nullable=True),
            sa.Column("remark", sa.Text(), nullable=True),
            sa.Column("attempt_count", sa.Integer(), nullable=False, server_default=sa.text("0")),
            sa.Column("last_checked_at", sa.DateTime(timezone=True), nullable=True),
            sa.Column("completed_at", sa.DateTime(timezone=True), nullable=True),
            sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
            sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
            sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
            sa.PrimaryKeyConstraint("id"),
        )

    indexes = _index_names(bind, "upstream_action_logs")
    for index_name, column in (
        ("ix_upstream_action_logs_user_id", "user_id"),
        ("ix_upstream_action_logs_order_id", "order_id"),
        ("ix_upstream_action_logs_order_refund_id", "order_refund_id"),
        ("ix_upstream_action_logs_instance_id", "instance_id"),
        ("ix_upstream_action_logs_cloud_server_id", "cloud_server_id"),
        ("ix_upstream_action_logs_upstream_id", "upstream_id"),
        ("ix_upstream_action_logs_action_type", "action_type"),
        ("ix_upstream_action_logs_resource_type", "resource_type"),
        ("ix_upstream_action_logs_resource_id", "resource_id"),
        ("ix_upstream_action_logs_source", "source"),
        ("ix_upstream_action_logs_status", "status"),
        ("ix_upstream_action_logs_upstream_task_id", "upstream_task_id"),
    ):
        if index_name not in indexes:
            op.create_index(index_name, "upstream_action_logs", [column])


def downgrade() -> None:
    bind = op.get_bind()
    tables = set(sa.inspect(bind).get_table_names())
    if "upstream_action_logs" in tables:
        op.drop_table("upstream_action_logs")
