"""Add DiscountRedemption.subscription

Revision ID: 8acb9ae6dfbe
Revises: a8b767b4a34a
Create Date: 2025-06-12 09:10:53.074644

"""

import sqlalchemy as sa
from alembic import op

# Polar Custom Imports

# revision identifiers, used by Alembic.
revision = "8acb9ae6dfbe"
down_revision = "a8b767b4a34a"
branch_labels: tuple[str] | None = None
depends_on: tuple[str] | None = None


def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column(
        "discount_redemptions", sa.Column("subscription_id", sa.Uuid(), nullable=True)
    )
    op.alter_column(
        "discount_redemptions", "checkout_id", existing_type=sa.UUID(), nullable=True
    )
    op.create_foreign_key(
        op.f("discount_redemptions_subscription_id_fkey"),
        "discount_redemptions",
        "subscriptions",
        ["subscription_id"],
        ["id"],
        ondelete="cascade",
    )

    op.execute(
        """
        UPDATE discount_redemptions AS dr
        SET subscription_id = (
            SELECT id
            FROM subscriptions
            WHERE subscriptions.checkout_id = dr.checkout_id
        )
        WHERE dr.checkout_id IS NOT NULL;
        """
    )

    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint(
        op.f("discount_redemptions_subscription_id_fkey"),
        "discount_redemptions",
        type_="foreignkey",
    )
    op.alter_column(
        "discount_redemptions", "checkout_id", existing_type=sa.UUID(), nullable=False
    )
    op.drop_column("discount_redemptions", "subscription_id")
    # ### end Alembic commands ###
