"""Set nullable JSONB values to SQL NULL

Revision ID: 2ffeb5016445
Revises: 46b68109883f
Create Date: 2025-06-18 14:25:20.413425

"""

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

# Polar Custom Imports

# revision identifiers, used by Alembic.
revision = "2ffeb5016445"
down_revision = "46b68109883f"
branch_labels: tuple[str] | None = None
depends_on: tuple[str] | None = None


def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.alter_column(
        "notifications",
        "payload",
        existing_type=postgresql.JSONB(astext_type=sa.Text()),
        nullable=False,
    )
    op.execute(
        """
        UPDATE orders
        SET tax_rate = NULL
        WHERE tax_rate = 'null'::jsonb
        """
    )
    op.execute(
        """
        UPDATE benefit_grants
        SET error = NULL
        WHERE error = 'null'::jsonb
        """
    )
    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.execute(
        """
        UPDATE orders
        SET tax_rate = 'null'::jsonb
        WHERE tax_rate IS NULL
        """
    )
    op.execute(
        """
        UPDATE benefit_grants
        SET error = 'null'::jsonb
        WHERE error IS NULL
        """
    )
    op.alter_column(
        "notifications",
        "payload",
        existing_type=postgresql.JSONB(astext_type=sa.Text()),
        nullable=True,
    )
    # ### end Alembic commands ###
