-- broker_ping_instance function
-- Updates the last_ping_at timestamp for a broker instance
-- Returns: p_retval (0=success, >0=error), p_errmsg (error message)

CREATE OR REPLACE FUNCTION broker_ping_instance(
    p_instance_id BIGINT,
    p_jobs_handled BIGINT DEFAULT NULL,
    OUT p_retval INTEGER,
    OUT p_errmsg TEXT
)
RETURNS RECORD
LANGUAGE plpgsql
AS $$
BEGIN
    p_retval := 0;
    p_errmsg := '';

    -- Validate instance ID
    IF p_instance_id IS NULL OR p_instance_id <= 0 THEN
        p_retval := 1;
        p_errmsg := 'Invalid instance ID';
        RETURN;
    END IF;

    -- Update ping timestamp
    IF p_jobs_handled IS NOT NULL THEN
        UPDATE broker_queueinstance
        SET last_ping_at = NOW(),
            jobs_handled = p_jobs_handled
        WHERE id_broker_queueinstance = p_instance_id;
    ELSE
        UPDATE broker_queueinstance
        SET last_ping_at = NOW()
        WHERE id_broker_queueinstance = p_instance_id;
    END IF;

    -- Check if instance was found
    IF NOT FOUND THEN
        p_retval := 2;
        p_errmsg := 'Instance not found';
        RETURN;
    END IF;

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

-- broker_shutdown_instance function
-- Marks a broker instance as shutdown
-- Returns: p_retval (0=success, >0=error), p_errmsg (error message)

CREATE OR REPLACE FUNCTION broker_shutdown_instance(
    p_instance_id BIGINT,
    OUT p_retval INTEGER,
    OUT p_errmsg TEXT
)
RETURNS RECORD
LANGUAGE plpgsql
AS $$
BEGIN
    p_retval := 0;
    p_errmsg := '';

    -- Validate instance ID
    IF p_instance_id IS NULL OR p_instance_id <= 0 THEN
        p_retval := 1;
        p_errmsg := 'Invalid instance ID';
        RETURN;
    END IF;

    -- Update instance status
    UPDATE broker_queueinstance
    SET status = 'shutdown',
        shutdown_at = NOW()
    WHERE id_broker_queueinstance = p_instance_id;

    -- Check if instance was found
    IF NOT FOUND THEN
        p_retval := 2;
        p_errmsg := 'Instance not found';
        RETURN;
    END IF;

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

-- Comments
COMMENT ON FUNCTION broker_ping_instance IS 'Updates the last ping timestamp for an instance';
COMMENT ON FUNCTION broker_shutdown_instance IS 'Marks an instance as shutdown';
