-- broker_add_job function
-- Adds a new job to the broker queue and sends a notification
-- Returns: p_retval (0=success, >0=error), p_errmsg (error message), p_job_id (new job ID)

CREATE OR REPLACE FUNCTION broker_add_job(
    p_job_name TEXT,
    p_execute_str TEXT,
    p_job_queue INTEGER DEFAULT 1,
    p_job_priority INTEGER DEFAULT 0,
    p_job_language TEXT DEFAULT 'sql',
    p_run_as TEXT DEFAULT NULL,
    p_schedule_id BIGINT DEFAULT NULL,
    p_depends_on TEXT[] DEFAULT NULL,
    OUT p_retval INTEGER,
    OUT p_errmsg TEXT,
    OUT p_job_id BIGINT
)
RETURNS RECORD
LANGUAGE plpgsql
AS $$
DECLARE
    v_notification_payload JSON;
BEGIN
    p_retval := 0;
    p_errmsg := '';
    p_job_id := NULL;

    -- Validate inputs
    IF p_job_name IS NULL OR p_job_name = '' THEN
        p_retval := 1;
        p_errmsg := 'Job name is required';
        RETURN;
    END IF;

    IF p_execute_str IS NULL OR p_execute_str = '' THEN
        p_retval := 2;
        p_errmsg := 'Execute string is required';
        RETURN;
    END IF;

    IF p_job_queue IS NULL OR p_job_queue <= 0 THEN
        p_retval := 3;
        p_errmsg := 'Invalid job queue number';
        RETURN;
    END IF;

    -- Insert new job
    INSERT INTO broker_jobs (
        job_name,
        job_priority,
        job_queue,
        job_language,
        execute_str,
        run_as,
        rid_broker_schedule,
        depends_on,
        complete_status
    ) VALUES (
        p_job_name,
        p_job_priority,
        p_job_queue,
        p_job_language,
        p_execute_str,
        p_run_as,
        p_schedule_id,
        p_depends_on,
        0  -- pending
    )
    RETURNING id_broker_jobs INTO p_job_id;

    -- Create notification payload
    v_notification_payload := json_build_object(
        'id', p_job_id,
        'job_name', p_job_name,
        'job_queue', p_job_queue,
        'job_priority', p_job_priority
    );

    -- Send notification to broker
    PERFORM pg_notify('broker.event', v_notification_payload::text);

EXCEPTION
    WHEN OTHERS THEN
        p_retval := 99;
        p_errmsg := SQLERRM;
        RAISE WARNING 'broker_add_job error: %', SQLERRM;
END;
$$;

-- Comments
COMMENT ON FUNCTION broker_add_job IS 'Adds a new job to the broker queue and sends a NOTIFY event';
