"""create events table

Revision ID: add_events_table
Revises: f18735338888
Create Date: 2024-03-19 10:00:00.000000

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy import inspect

# revision identifiers, used by Alembic.
revision = 'add_events_table'
down_revision = 'f18735338888'
branch_labels = None
depends_on = None

def upgrade():
    conn = op.get_bind()
    inspector = inspect(conn)
    tables = inspector.get_table_names()
    
    if 'events' not in tables:
        op.create_table(
            'events',
            sa.Column('id', sa.Integer, primary_key=True),
            sa.Column('event_type', sa.String(50), nullable=False),
            sa.Column('user_id', sa.Integer, sa.ForeignKey('user.id'), nullable=True),
            sa.Column('timestamp', sa.DateTime, nullable=False),
            sa.Column('details', sa.JSON),
            sa.Column('ip_address', sa.String(45)),
            sa.Column('user_agent', sa.String(255)),
        )
        op.create_index('idx_events_event_type', 'events', ['event_type'])
        op.create_index('idx_events_timestamp', 'events', ['timestamp'])
        op.create_index('idx_events_user_id', 'events', ['user_id'])

def downgrade():
    op.drop_index('idx_events_event_type', table_name='events')
    op.drop_index('idx_events_timestamp', table_name='events')
    op.drop_index('idx_events_user_id', table_name='events')
    op.drop_table('events') 