DO $$
DECLARE
    trigger_name TEXT := 'trigger_audit_log';
    rec RECORD;
BEGIN
    -- Loop through all triggers with the name 'trigger_audit_log'
    FOR rec IN
        SELECT pg_class.relname AS table_name
        FROM pg_trigger
        JOIN pg_class ON pg_trigger.tgrelid = pg_class.oid
        WHERE pg_trigger.tgname = trigger_name
    LOOP
        -- Drop the trigger from the identified table
        EXECUTE format('DROP TRIGGER IF EXISTS %I ON %I;', trigger_name, rec.table_name);
    END LOOP;
END $$;

DO $$ 
DECLARE
    table_name TEXT;
    tables TEXT[] := ARRAY['users', 'user_details', 'designations', 'departments', 'permissions', 'roles', 'role_permissions', 'user_roles', 'user_permissions', 'language_contents', 'menu', 'menu_items', 'master_entities', 'master_entity_line_items', 'notification_templates', 'notification_template_assignments']; -- List of tables for triggers
BEGIN
    -- Loop through each table in the list
    -- FOR table_name IN
    --     SELECT table_name
    --     FROM information_schema.tables
    --     WHERE table_schema = 'public'
    FOREACH table_name IN ARRAY tables
    LOOP
        -- Generate and execute the CREATE TRIGGER statement for each table
        EXECUTE format('
            CREATE TRIGGER trigger_audit_log
            AFTER UPDATE OR DELETE ON %I
            FOR EACH ROW EXECUTE FUNCTION audit_trigger();',
            table_name
        );
    END LOOP;
END $$;