"""Update Organization.status and add Organization.initially_reviewed_at

Revision ID: d6809d0a2f67
Revises: cd0255e61066
Create Date: 2025-11-04 09:42:54.542971

"""

import sqlalchemy as sa
from alembic import op

# Polar Custom Imports

# revision identifiers, used by Alembic.
revision = "d6809d0a2f67"
down_revision = "cd0255e61066"
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(
        "organizations",
        sa.Column("initially_reviewed_at", sa.TIMESTAMP(timezone=True), nullable=True),
    )
    op.execute(
        """
        UPDATE organizations
        SET status = 'initial_review'
        WHERE status = 'under_review' AND next_review_threshold = 0
        """
    )
    op.execute(
        """
        UPDATE organizations
        SET status = 'ongoing_review'
        WHERE status = 'under_review' AND next_review_threshold > 0
        """
    )
    op.execute(
        """
        UPDATE organizations
        SET initially_reviewed_at = status_updated_at
        WHERE status IN ('active', 'ongoing_review', 'denied')
        """
    )

    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column("organizations", "initially_reviewed_at")
    op.execute(
        """
        UPDATE organizations
        SET status = 'under_review'
        WHERE status IN ('initial_review', 'ongoing_review')
        """
    )
    # ### end Alembic commands ###
