-- Fix delegated user sessions trigger conflict
-- The original BEFORE INSERT trigger caused recursive table access errors
-- when trying to clean up expired sessions during new session creation

USE whp;

-- Drop the problematic trigger that causes recursive table access
DROP TRIGGER IF EXISTS cleanup_expired_delegated_sessions;

-- Create a simpler, safer approach using an AFTER INSERT trigger
-- This avoids the recursive conflict by running cleanup after the insert
DELIMITER //
CREATE TRIGGER IF NOT EXISTS cleanup_expired_delegated_sessions_safe
    AFTER INSERT ON delegated_user_sessions
    FOR EACH ROW
BEGIN
    -- Only run cleanup occasionally to avoid performance issues
    -- Use modulo to run cleanup roughly 10% of the time
    IF (RAND() * 100) < 10 THEN
        DELETE FROM delegated_user_sessions 
        WHERE expires_at < NOW() 
        AND id != NEW.id; -- Don't delete the session we just created
    END IF;
END//
DELIMITER ;