"""add owner_id to group

Revision ID: 36ed70229177
Revises: b5ace31192c3
Create Date: 2026-03-28 13:26:31.817104

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision: str = '36ed70229177'
down_revision: Union[str, Sequence[str], None] = 'b5ace31192c3'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    """Upgrade schema."""
    # 1. Add column as nullable
    op.add_column('groups', sa.Column('owner_id', sa.UUID(), nullable=True))
    op.create_index(op.f('ix_groups_owner_id'), 'groups', ['owner_id'], unique=False)
    op.create_foreign_key(None, 'groups', 'users', ['owner_id'], ['id'], ondelete='CASCADE')

    # 2. Update existing groups with an owner (using the first manager or any member)
    op.execute("""
        UPDATE groups g
        SET owner_id = (
            SELECT user_id 
            FROM group_members 
            WHERE group_id = g.id 
            ORDER BY (CASE WHEN role::text = 'MANAGER' THEN 0 ELSE 1 END), user_id
            LIMIT 1
        )
    """)

    # 3. For any group that still has NULL (unlikely), set to the first user in the system
    op.execute("""
        UPDATE groups
        SET owner_id = (SELECT id FROM users LIMIT 1)
        WHERE owner_id IS NULL
    """)

    # 4. Set NOT NULL constraint
    op.alter_column('groups', 'owner_id', nullable=False)


def downgrade() -> None:
    """Downgrade schema."""
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint(None, 'groups', type_='foreignkey')
    op.drop_index(op.f('ix_groups_owner_id'), table_name='groups')
    op.drop_column('groups', 'owner_id')
    # ### end Alembic commands ###
