-- Migration 00004: Rate Limiting Function

CREATE OR REPLACE FUNCTION public.check_rate_limit(
    p_action TEXT,
    p_max_requests INT,
    p_window_seconds INT
)
RETURNS BOOLEAN
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
DECLARE
    v_user_id UUID;
    v_count INT;
    v_window_start TIMESTAMPTZ;
BEGIN
    v_user_id := auth.uid();
    IF v_user_id IS NULL THEN
        RAISE EXCEPTION 'UNAUTHORIZED: User must be authenticated to check rate limit';
    END IF;

    v_window_start := NOW() - (p_window_seconds || ' seconds')::INTERVAL;

    -- Clean up old events for this user/action
    DELETE FROM public.rate_limit_events
    WHERE user_id = v_user_id
      AND action = p_action
      AND created_at < v_window_start;

    -- Count requests in current window
    SELECT COUNT(*) INTO v_count
    FROM public.rate_limit_events
    WHERE user_id = v_user_id
      AND action = p_action
      AND created_at >= v_window_start;

    IF v_count >= p_max_requests THEN
        RETURN FALSE;
    END IF;

    -- Record request
    INSERT INTO public.rate_limit_events (user_id, action)
    VALUES (v_user_id, p_action);

    RETURN TRUE;
END;
$$;
