"""Phase 7.4 — Campaign Engine (campaign applications)."""
from alembic import op
import sqlalchemy as sa

revision = "0005_phase_74_campaigns"
down_revision = "0004_phase_73_rewards"
branch_labels = None
depends_on = None


def upgrade():
    op.create_table(
        "campaign_applications",
        sa.Column("id", sa.CHAR(length=36), primary_key=True),
        sa.Column("tenant_id", sa.CHAR(length=36), nullable=False),
        sa.Column("campaign_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("point_account_id", sa.CHAR(length=36), nullable=False),
        sa.Column("rule_version", sa.Integer(), nullable=False),
        sa.Column(
            "points_granted", sa.Integer(), nullable=False, server_default="0"
        ),
        sa.Column("ledger_entry_id", sa.CHAR(length=36), nullable=True),
        sa.Column("status", sa.String(length=20), nullable=False),
        sa.Column("idempotency_key", sa.String(length=100), nullable=True),
        sa.Column("actor_user_id", sa.String(length=100), nullable=True),
        sa.Column("metadata_json", sa.JSON(), nullable=True),
        sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
        sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
        sa.UniqueConstraint(
            "tenant_id",
            "idempotency_key",
            name="uq_campaign_applications_tenant_idempotency",
        ),
    )
    op.create_index(
        "ix_campaign_applications_campaign_member",
        "campaign_applications",
        ["tenant_id", "campaign_id", "member_id"],
    )


def downgrade():
    op.drop_index(
        "ix_campaign_applications_campaign_member",
        table_name="campaign_applications",
    )
    op.drop_table("campaign_applications")
