"""Make Subscription.scheduler_locked_at a nullable datetime

Revision ID: 3ee37a022b30
Revises: 4b946a507b1e
Create Date: 2025-09-04 09:35:19.562041

"""

import sqlalchemy as sa
from alembic import op

# Polar Custom Imports

# revision identifiers, used by Alembic.
revision = "3ee37a022b30"
down_revision = "4b946a507b1e"
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(
        "subscriptions",
        sa.Column("scheduler_locked_at", sa.TIMESTAMP(timezone=True), nullable=True),
    )
    op.create_index(
        op.f("ix_subscriptions_scheduler_locked_at"),
        "subscriptions",
        ["scheduler_locked_at"],
        unique=False,
    )

    op.execute(
        "UPDATE subscriptions SET scheduler_locked_at = NOW() WHERE scheduler_locked IS TRUE"
    )

    op.drop_index(op.f("ix_subscriptions_scheduler_locked"), table_name="subscriptions")
    op.drop_column("subscriptions", "scheduler_locked")
    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column(
        "subscriptions",
        sa.Column("scheduler_locked", sa.BOOLEAN(), autoincrement=False, nullable=True),
    )
    op.create_index(
        op.f("ix_subscriptions_scheduler_locked"),
        "subscriptions",
        ["scheduler_locked"],
        unique=False,
    )

    op.execute(
        "UPDATE subscriptions SET scheduler_locked = TRUE WHERE scheduler_locked_at IS NOT NULL"
    )
    op.execute(
        "UPDATE subscriptions SET scheduler_locked = FALSE WHERE scheduler_locked_at IS NULL"
    )

    op.alter_column(
        "subscriptions",
        "scheduler_locked",
        existing_type=sa.BOOLEAN(),
        nullable=False,
        existing_nullable=True,
    )

    op.drop_index(
        op.f("ix_subscriptions_scheduler_locked_at"), table_name="subscriptions"
    )
    op.drop_column("subscriptions", "scheduler_locked_at")
    # ### end Alembic commands ###
