"""Phase 7.2 — immutable point ledger."""
from alembic import op
import sqlalchemy as sa

revision = "0003_phase_72_points"
down_revision = "0002_phase_71_membership"
branch_labels = None
depends_on = None


def upgrade():
    op.create_table(
        "point_ledger_entries",
        sa.Column("id", sa.CHAR(length=36), primary_key=True),
        sa.Column("tenant_id", sa.CHAR(length=36), nullable=False),
        sa.Column("point_account_id", sa.CHAR(length=36), nullable=False),
        sa.Column("program_id", sa.CHAR(length=36), nullable=False),
        sa.Column("member_id", sa.CHAR(length=36), nullable=False),
        sa.Column("entry_type", sa.String(length=30), nullable=False),
        sa.Column("amount", sa.Integer(), nullable=False),
        sa.Column("balance_after", sa.Integer(), nullable=False),
        sa.Column("idempotency_key", sa.String(length=100), nullable=True),
        sa.Column("reference_type", sa.String(length=50), nullable=True),
        sa.Column("reference_id", sa.String(length=100), nullable=True),
        sa.Column("reason", sa.String(length=500), nullable=True),
        sa.Column("metadata_json", sa.JSON(), nullable=True),
        sa.Column("expires_at", sa.DateTime(timezone=True), nullable=True),
        sa.Column("actor_user_id", sa.String(length=100), nullable=True),
        sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
        sa.UniqueConstraint(
            "tenant_id",
            "idempotency_key",
            name="uq_point_ledger_tenant_idempotency",
        ),
    )
    op.create_index(
        "ix_point_ledger_account",
        "point_ledger_entries",
        ["tenant_id", "point_account_id"],
    )
    op.create_index(
        "ix_point_ledger_member", "point_ledger_entries", ["tenant_id", "member_id"]
    )
    op.create_index(
        "ix_point_ledger_type", "point_ledger_entries", ["tenant_id", "entry_type"]
    )
    op.create_index(
        "ix_point_ledger_created", "point_ledger_entries", ["tenant_id", "created_at"]
    )
    op.create_index(
        "ix_point_ledger_expires", "point_ledger_entries", ["tenant_id", "expires_at"]
    )


def downgrade():
    op.drop_index("ix_point_ledger_expires", table_name="point_ledger_entries")
    op.drop_index("ix_point_ledger_created", table_name="point_ledger_entries")
    op.drop_index("ix_point_ledger_type", table_name="point_ledger_entries")
    op.drop_index("ix_point_ledger_member", table_name="point_ledger_entries")
    op.drop_index("ix_point_ledger_account", table_name="point_ledger_entries")
    op.drop_table("point_ledger_entries")
