"""manual_notification_fix

Revision ID: b1ca95289d88
Revises: b83b61f15175
Create Date: 2025-12-29 13:14:38.291752

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa
import sqlmodel


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


def upgrade() -> None:
    # 1. Create Notification Table if not exists
    # Use SQLAlchemy inspector to check table existence
    conn = op.get_bind()
    inspector = sa.inspect(conn)
    tables = inspector.get_table_names()
    
    if 'notification' not in tables:
        op.create_table('notification',
            sa.Column('id', sa.Integer(), nullable=False),
            sa.Column('user_id', sa.Integer(), nullable=False),
            sa.Column('type', sa.Enum('SHOW_ALERT', 'SIT_IN_ALERT', 'CHASE_SONG_ALERT', name='notificationtype'), nullable=False),
            sa.Column('title', sa.String(), nullable=False),
            sa.Column('message', sa.String(), nullable=False),
            sa.Column('link', sa.String(), nullable=True),
            sa.Column('is_read', sa.Boolean(), nullable=False, server_default=sa.text('0')),
            sa.Column('created_at', sa.DateTime(), nullable=False),
            sa.PrimaryKeyConstraint('id')
        )
        op.create_index(op.f('ix_notification_user_id'), 'notification', ['user_id'], unique=False)
        op.create_foreign_key('fk_notification_user', 'notification', 'user', ['user_id'], ['id'])

    # 2. Add missing columns to UserVerticalPreference if they don't exist
    columns = [c['name'] for c in inspector.get_columns('userverticalpreference')]
    
    # Explicitly create type execution for Postgres
    from sqlalchemy.dialects import postgresql
    enum_type = postgresql.ENUM('HEADLINER', 'MAIN_STAGE', 'SUPPORTING', name='preferencetier')
    enum_type.create(op.get_bind(), checkfirst=True)

    with op.batch_alter_table('userverticalpreference', schema=None) as batch_op:
        if 'tier' not in columns:
            batch_op.add_column(sa.Column('tier', sa.Enum('HEADLINER', 'MAIN_STAGE', 'SUPPORTING', name='preferencetier'), server_default='MAIN_STAGE', nullable=False))
        if 'notify_on_show' not in columns:
            batch_op.add_column(sa.Column('notify_on_show', sa.Boolean(), server_default=sa.text('1'), nullable=False))


def downgrade() -> None:
    # Downgrade logic
    with op.batch_alter_table('userverticalpreference', schema=None) as batch_op:
        batch_op.drop_column('notify_on_show')
        batch_op.drop_column('tier')
        
    op.drop_index(op.f('ix_notification_user_id'), table_name='notification')
    op.drop_table('notification')
