"""add uuid to notifications table

Revision ID: 70f12f8c0218
Revises: aa7802092404
Create Date: 2024-12-18 14:35:54.901437

"""

from uuid import uuid4

import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql

# revision identifiers, used by Alembic.
revision = '70f12f8c0218'
down_revision = 'aa7802092404'
branch_labels = None
depends_on = None


def upgrade():
    op.add_column(
        'notifications',
        sa.Column('uuid', postgresql.UUID(as_uuid=True), nullable=True),
    )

    notifications_helper = sa.Table(
        'notifications',
        sa.MetaData(),
        sa.Column('id', sa.Integer(), nullable=False),
    )
    connection = op.get_bind()
    for notification in connection.execute(notifications_helper.select()):
        op.execute(f"""
            UPDATE notifications
            SET uuid = '{uuid4()}'
            WHERE notifications.id = {notification.id}
            """)

    op.alter_column('notifications', 'uuid', nullable=False)
    op.create_unique_constraint(
        'notifications_uuid_key', 'notifications', ['uuid']
    )


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table('notifications', schema=None) as batch_op:
        batch_op.drop_constraint('notifications_uuid_key', type_='unique')
        batch_op.drop_column('uuid')

    # ### end Alembic commands ###
