"""fix updated_at trigger

Revision ID: fix_updated_at_trigger
Revises: add_status_details
Create Date: 2024-03-19 12:00:00.000000

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

# revision identifiers, used by Alembic.
revision = 'fix_updated_at_trigger'
down_revision = 'add_status_details'
branch_labels = None
depends_on = None

def upgrade():
    # Drop the existing trigger if it exists
    op.execute("DROP TRIGGER IF EXISTS update_instances_updated_at ON instances")
    op.execute("DROP FUNCTION IF EXISTS update_updated_at_column()")
    
    # Create the trigger function
    op.execute("""
        CREATE OR REPLACE FUNCTION update_updated_at_column()
        RETURNS TRIGGER AS $$
        BEGIN
            NEW.updated_at = CURRENT_TIMESTAMP;
            RETURN NEW;
        END;
        $$ language 'plpgsql';
    """)
    
    # Create the trigger
    op.execute("""
        CREATE TRIGGER update_instances_updated_at
            BEFORE UPDATE ON instances
            FOR EACH ROW
            EXECUTE FUNCTION update_updated_at_column();
    """)

def downgrade():
    # Drop the trigger and function
    op.execute("DROP TRIGGER IF EXISTS update_instances_updated_at ON instances")
    op.execute("DROP FUNCTION IF EXISTS update_updated_at_column()") 