"""Add app_logs table for audit, usage, and error logging."""

from alembic import op

revision = "0010"
down_revision = "0009"


def upgrade() -> None:
    op.execute("""
        CREATE TABLE IF NOT EXISTS app_logs (
            id SERIAL PRIMARY KEY,
            category TEXT NOT NULL,
            user_id INTEGER REFERENCES users(id) ON DELETE SET NULL,
            username TEXT,
            action TEXT,
            endpoint TEXT,
            method TEXT,
            status_code INTEGER,
            duration_ms REAL,
            ip_address TEXT,
            details TEXT,
            created_at TIMESTAMPTZ DEFAULT now()
        )
    """)
    op.execute("CREATE INDEX IF NOT EXISTS ix_app_logs_category ON app_logs (category)")
    op.execute("CREATE INDEX IF NOT EXISTS ix_app_logs_user_id ON app_logs (user_id)")
    op.execute("CREATE INDEX IF NOT EXISTS ix_app_logs_created_at ON app_logs (created_at)")
    op.execute(
        "CREATE INDEX IF NOT EXISTS ix_app_logs_category_created_at "
        "ON app_logs (category, created_at DESC)"
    )


def downgrade() -> None:
    op.execute("DROP INDEX IF EXISTS ix_app_logs_category_created_at")
    op.execute("DROP INDEX IF EXISTS ix_app_logs_created_at")
    op.execute("DROP INDEX IF EXISTS ix_app_logs_user_id")
    op.execute("DROP INDEX IF EXISTS ix_app_logs_category")
    op.execute("DROP TABLE IF EXISTS app_logs")
