"""Add BillingEntry type, discount_id and discount_amount

Revision ID: a7c4fe33ecec
Revises: b5ffc01faa80
Create Date: 2025-08-28 12:03:51.464409

"""

import sqlalchemy as sa
from alembic import op

# Polar Custom Imports

# revision identifiers, used by Alembic.
revision = "a7c4fe33ecec"
down_revision = "b5ffc01faa80"
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("billing_entry", sa.Column("type", sa.String(), nullable=True))
    op.execute(
        """
        UPDATE billing_entry
        SET type = CASE
            WHEN product_prices.amount_type = 'metered_unit' THEN 'metered'
            ELSE 'cycle'
        END
        FROM product_prices
        WHERE billing_entry.product_price_id = product_prices.id
        """
    )
    op.alter_column("billing_entry", "type", nullable=False)

    op.add_column("billing_entry", sa.Column("discount_id", sa.Uuid(), nullable=True))
    op.add_column(
        "billing_entry", sa.Column("discount_amount", sa.Integer(), nullable=True)
    )
    op.create_index(
        op.f("ix_billing_entry_type"), "billing_entry", ["type"], unique=False
    )
    op.create_foreign_key(
        op.f("billing_entry_discount_id_fkey"),
        "billing_entry",
        "discounts",
        ["discount_id"],
        ["id"],
        ondelete="restrict",
    )
    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint(
        op.f("billing_entry_discount_id_fkey"), "billing_entry", type_="foreignkey"
    )
    op.drop_index(op.f("ix_billing_entry_type"), table_name="billing_entry")
    op.drop_column("billing_entry", "discount_id")
    op.drop_column("billing_entry", "discount_amount")
    op.drop_column("billing_entry", "type")
    # ### end Alembic commands ###
