"""add status to organization

Revision ID: 24bff4469bc0
Revises: 2c68ca24df26
Create Date: 2025-07-28 14:43:59.406269

"""

import sqlalchemy as sa
from alembic import op

# Polar Custom Imports
from polar.kit.extensions.sqlalchemy.types import StringEnum
from polar.models.organization import Organization, OrganizationStatus

# revision identifiers, used by Alembic.
revision = "24bff4469bc0"
down_revision = "2c68ca24df26"
branch_labels: tuple[str] | None = None
depends_on: tuple[str] | None = None


def upgrade() -> None:
    op.add_column(
        "organizations",
        sa.Column(
            "status",
            StringEnum(OrganizationStatus),
            nullable=True,
            default=OrganizationStatus.CREATED.value,
        ),
    )

    # Backfill existing organizations with Account status
    op.execute(
        """
        UPDATE organizations
        SET status = a.status
        FROM accounts a
        WHERE organizations.account_id = a.id;
        """
    )

    # Update the missing statuses to the default value
    op.execute(
        """
        UPDATE organizations
        SET status = 'created'
        WHERE status IS NULL;
        """
    )

    # Make status non-nullable, default to CREATED for new rows
    op.alter_column(
        "organizations",
        "status",
        nullable=False,
    )


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column("organizations", "status")
    # ### end Alembic commands ###
