"""add account_id to target_lists (keep team_id)

Revision ID: 2c6aabd89bc6
Revises: 78fc200abac1
Create Date: 2026-04-09 00:00:00.000000
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa

revision: str = '2c6aabd89bc6'
down_revision: Union[str, None] = '78fc200abac1'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    op.add_column('target_lists', sa.Column('account_id', sa.UUID(), nullable=True))
    op.create_foreign_key(
        'fk_target_lists_account_id', 'target_lists', 'accounts',
        ['account_id'], ['id'], ondelete='CASCADE',
    )

    # Primary: team_id → team admin user → account_id
    op.execute("""
        UPDATE target_lists tl
        SET account_id = u.account_id
        FROM users u
        WHERE u.team_id = tl.team_id
          AND u.is_team_admin = TRUE
          AND u.account_id IS NOT NULL
          AND tl.account_id IS NULL
    """)

    # Fallback: created_by → users.account_id
    op.execute("""
        UPDATE target_lists tl
        SET account_id = u.account_id
        FROM users u
        WHERE tl.created_by = u.id
          AND u.account_id IS NOT NULL
          AND tl.account_id IS NULL
    """)

    result = op.get_bind().execute(
        sa.text("SELECT COUNT(*) FROM target_lists WHERE account_id IS NULL")
    )
    count = result.scalar()
    if count > 0:
        raise RuntimeError(
            f"ROLLBACK: {count} target_lists rows have NULL account_id. "
            "No team admin found for these teams. Resolve before re-running."
        )

    op.alter_column('target_lists', 'account_id', nullable=False)
    op.create_index('ix_target_lists_account_id', 'target_lists', ['account_id'])


def downgrade() -> None:
    op.drop_index('ix_target_lists_account_id', table_name='target_lists')
    op.drop_constraint('fk_target_lists_account_id', 'target_lists', type_='foreignkey')
    op.drop_column('target_lists', 'account_id')
