-- broker_register_instance function
-- Registers a new broker instance in the database
-- Returns: p_retval (0=success, >0=error), p_errmsg (error message), p_instance_id (new instance ID)

CREATE OR REPLACE FUNCTION broker_register_instance(
    p_name TEXT,
    p_hostname TEXT,
    p_pid INTEGER,
    p_version TEXT,
    p_queue_count INTEGER,
    OUT p_retval INTEGER,
    OUT p_errmsg TEXT,
    OUT p_instance_id BIGINT
)
RETURNS RECORD
LANGUAGE plpgsql
AS $$
DECLARE
    v_active_count INTEGER;
BEGIN
    p_retval := 0;
    p_errmsg := '';
    p_instance_id := NULL;

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

    IF p_hostname IS NULL OR p_hostname = '' THEN
        p_retval := 2;
        p_errmsg := 'Hostname is required';
        RETURN;
    END IF;

    -- Check for existing active instances
    -- Only one broker instance should be active per database
    SELECT COUNT(*)
    INTO v_active_count
    FROM broker_queueinstance
    WHERE status = 'active';

    IF v_active_count > 0 THEN
        p_retval := 3;
        p_errmsg := 'Another broker instance is already active in this database. Only one broker instance per database is allowed.';
        RETURN;
    END IF;

    -- Insert new instance
    INSERT INTO broker_queueinstance (
        name,
        hostname,
        pid,
        version,
        status,
        queue_count,
        started_at,
        last_ping_at
    ) VALUES (
        p_name,
        p_hostname,
        p_pid,
        p_version,
        'active',
        p_queue_count,
        NOW(),
        NOW()
    )
    RETURNING id_broker_queueinstance INTO p_instance_id;

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

-- Comments
COMMENT ON FUNCTION broker_register_instance IS 'Registers a new broker instance';
