"""add performing partner to clients and engagements

Revision ID: 20260805_performing_partner
Revises: 20260725_client_groups_family_tracking
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy import inspect

revision = "20260805_performing_partner"
down_revision = "20260725_client_groups_family_tracking"
branch_labels = None
depends_on = None

def _has_column(table, column):
    return column in {c["name"] for c in inspect(op.get_bind()).get_columns(table)}

def _has_index(table, name):
    return name in {i["name"] for i in inspect(op.get_bind()).get_indexes(table)}

def upgrade():
    if not _has_column("clients", "default_performing_partner_user_id"):
        op.add_column("clients", sa.Column("default_performing_partner_user_id", sa.Integer(), nullable=True))
        op.create_foreign_key("fk_clients_default_performing_partner", "clients", "users", ["default_performing_partner_user_id"], ["id"], ondelete="SET NULL")
    if not _has_index("clients", "ix_clients_default_performing_partner_user_id"):
        op.create_index("ix_clients_default_performing_partner_user_id", "clients", ["default_performing_partner_user_id"])
    if not _has_column("client_service_subscriptions", "performing_partner_user_id"):
        op.add_column("client_service_subscriptions", sa.Column("performing_partner_user_id", sa.Integer(), nullable=True))
        op.create_foreign_key("fk_css_performing_partner", "client_service_subscriptions", "users", ["performing_partner_user_id"], ["id"], ondelete="SET NULL")
    if not _has_index("client_service_subscriptions", "ix_client_service_subscriptions_performing_partner_user_id"):
        op.create_index("ix_client_service_subscriptions_performing_partner_user_id", "client_service_subscriptions", ["performing_partner_user_id"])
    op.execute("""UPDATE client_service_subscriptions SET performing_partner_user_id = assigned_partner_user_id WHERE performing_partner_user_id IS NULL""")

def downgrade():
    if _has_index("client_service_subscriptions", "ix_client_service_subscriptions_performing_partner_user_id"):
        op.drop_index("ix_client_service_subscriptions_performing_partner_user_id", table_name="client_service_subscriptions")
    if _has_column("client_service_subscriptions", "performing_partner_user_id"):
        op.drop_constraint("fk_css_performing_partner", "client_service_subscriptions", type_="foreignkey")
        op.drop_column("client_service_subscriptions", "performing_partner_user_id")
    if _has_index("clients", "ix_clients_default_performing_partner_user_id"):
        op.drop_index("ix_clients_default_performing_partner_user_id", table_name="clients")
    if _has_column("clients", "default_performing_partner_user_id"):
        op.drop_constraint("fk_clients_default_performing_partner", "clients", type_="foreignkey")
        op.drop_column("clients", "default_performing_partner_user_id")
