"""add organization_id to members table

Revision ID: 2990d8555091
Revises: e469a3ec2161
Create Date: 2025-11-20 08:14:34.672770

"""

import sqlalchemy as sa
from alembic import op

# Polar Custom Imports

# revision identifiers, used by Alembic.
revision = "2990d8555091"
down_revision = "e469a3ec2161"
branch_labels: tuple[str] | None = None
depends_on: tuple[str] | None = None


def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    # Add organization_id as nullable first
    op.add_column("members", sa.Column("organization_id", sa.Uuid(), nullable=True))

    # Populate organization_id from customer relationship
    op.execute("""
        UPDATE members
        SET organization_id = customers.organization_id
        FROM customers
        WHERE members.customer_id = customers.id
    """)

    # Make organization_id non-nullable
    op.alter_column("members", "organization_id", nullable=False)

    op.create_index(
        op.f("ix_members_organization_id"), "members", ["organization_id"], unique=False
    )
    op.create_foreign_key(
        op.f("members_organization_id_fkey"),
        "members",
        "organizations",
        ["organization_id"],
        ["id"],
        ondelete="restrict",
    )
    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint(
        op.f("members_organization_id_fkey"), "members", type_="foreignkey"
    )
    op.drop_index(op.f("ix_members_organization_id"), table_name="members")
    op.drop_column("members", "organization_id")
    # ### end Alembic commands ###
