"""add email templates table

Revision ID: c770e08966b4
Revises: e7e4ff171f7a
Create Date: 2025-06-02 14:00:05.521776

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

# revision identifiers, used by Alembic.
revision = 'c770e08966b4'
down_revision = 'e7e4ff171f7a'
branch_labels = None
depends_on = None


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    conn = op.get_bind()
    inspector = inspect(conn)
    tables = inspector.get_table_names()
    
    if 'notification' in tables:
        op.drop_table('notification')
    
    op.create_table('email_template',
        sa.Column('id', sa.Integer(), nullable=False),
        sa.Column('name', sa.String(length=100), nullable=False),
        sa.Column('subject', sa.String(length=200), nullable=False),
        sa.Column('body', sa.Text(), nullable=False),
        sa.Column('created_at', sa.DateTime(), nullable=True),
        sa.Column('updated_at', sa.DateTime(), nullable=True),
        sa.PrimaryKeyConstraint('id'),
        sa.UniqueConstraint('name')
    )
    
    # Check for existing indexes before dropping them
    with op.batch_alter_table('events', schema=None) as batch_op:
        batch_op.alter_column('details',
               existing_type=postgresql.JSONB(astext_type=sa.Text()),
               type_=sa.JSON(),
               existing_nullable=True)
        
        # Get existing indexes
        indexes = inspector.get_indexes('events')
        index_names = [idx['name'] for idx in indexes]
        
        # Only drop indexes if they exist
        if 'idx_events_event_type' in index_names:
            batch_op.drop_index(batch_op.f('idx_events_event_type'))
        if 'idx_events_timestamp' in index_names:
            batch_op.drop_index(batch_op.f('idx_events_timestamp'))
        if 'idx_events_user_id' in index_names:
            batch_op.drop_index(batch_op.f('idx_events_user_id'))

    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table('events', schema=None) as batch_op:
        batch_op.create_index(batch_op.f('idx_events_user_id'), ['user_id'], unique=False)
        batch_op.create_index(batch_op.f('idx_events_timestamp'), ['timestamp'], unique=False)
        batch_op.create_index(batch_op.f('idx_events_event_type'), ['event_type'], unique=False)
        batch_op.alter_column('details',
               existing_type=sa.JSON(),
               type_=postgresql.JSONB(astext_type=sa.Text()),
               existing_nullable=True)

    op.drop_table('email_template')
    # ### end Alembic commands ### 