"""Add metadata and checkout_id to Order and Subscription

Revision ID: dc0951eede55
Revises: 3962174f6753
Create Date: 2024-10-07 11:51:05.176493

"""

import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql

# Polar Custom Imports

# revision identifiers, used by Alembic.
revision = "dc0951eede55"
down_revision = "3962174f6753"
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("orders", sa.Column("checkout_id", sa.Uuid(), nullable=True))

    op.add_column(
        "orders",
        sa.Column(
            "user_metadata", postgresql.JSONB(astext_type=sa.Text()), nullable=True
        ),
    )
    op.execute(
        """
        UPDATE orders
        SET user_metadata = '{}'
        """
    )
    op.alter_column("orders", "user_metadata", nullable=False)

    op.create_index(
        op.f("ix_orders_checkout_id"), "orders", ["checkout_id"], unique=False
    )
    op.create_foreign_key(
        op.f("orders_checkout_id_fkey"),
        "orders",
        "checkouts",
        ["checkout_id"],
        ["id"],
        ondelete="set null",
    )
    op.add_column("subscriptions", sa.Column("checkout_id", sa.Uuid(), nullable=True))

    op.add_column(
        "subscriptions",
        sa.Column(
            "user_metadata", postgresql.JSONB(astext_type=sa.Text()), nullable=True
        ),
    )
    op.execute(
        """
        UPDATE subscriptions
        SET user_metadata = '{}'
        """
    )
    op.alter_column("subscriptions", "user_metadata", nullable=False)

    op.create_index(
        op.f("ix_subscriptions_checkout_id"),
        "subscriptions",
        ["checkout_id"],
        unique=False,
    )
    op.create_foreign_key(
        op.f("subscriptions_checkout_id_fkey"),
        "subscriptions",
        "checkouts",
        ["checkout_id"],
        ["id"],
        ondelete="set null",
    )
    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint(
        op.f("subscriptions_checkout_id_fkey"), "subscriptions", type_="foreignkey"
    )
    op.drop_index(op.f("ix_subscriptions_checkout_id"), table_name="subscriptions")
    op.drop_column("subscriptions", "user_metadata")
    op.drop_column("subscriptions", "checkout_id")
    op.drop_constraint(op.f("orders_checkout_id_fkey"), "orders", type_="foreignkey")
    op.drop_index(op.f("ix_orders_checkout_id"), table_name="orders")
    op.drop_column("orders", "user_metadata")
    op.drop_column("orders", "checkout_id")
    # ### end Alembic commands ###
