
CREATE OR REPLACE FUNCTION tcg.public.FN_TCG_User_Get_Many (
      a_get_all_user BOOLEAN
    , a_get_inactive_user BOOLEAN
	, a_user_ids TEXT
    , a_require_all_id_filters_met BOOLEAN
    , a_require_any_id_filters_met BOOLEAN
)
RETURNS TABLE (
      user_id INT
    , user_auth0_id VARCHAR(200)
    , firstname TEXT
    , surname TEXT
    , email VARCHAR(256)
    , is_email_verified BOOLEAN
    , is_super_user BOOLEAN
    , active BOOLEAN
    , created_on TIMESTAMP
    , created_by_user_id INT
	, updated_last_on TIMESTAMP
	, updated_last_by_user_id INT
    , change_set_id INT
)
LANGUAGE plpgsql
AS $$
DECLARE
    v_get_all_user BOOLEAN;
    v_get_inactive_user BOOLEAN;
    v_require_all_id_filters_met BOOLEAN;
    v_require_any_id_filters_met BOOLEAN;
	v_user_ids TEXT;
BEGIN
	v_get_all_user := COALESCE(a_get_all_user, FALSE);
    v_get_inactive_user := COALESCE(a_get_inactive_user, FALSE);
	v_user_ids := TRIM(COALESCE(a_user_ids, ''));
    v_require_all_id_filters_met := COALESCE(a_require_all_id_filters_met, FALSE);
    v_require_any_id_filters_met := COALESCE(a_require_any_id_filters_met, FALSE);
	
	-- Outputs
    RETURN QUERY SELECT
          TCG_USER.user_id
        , TCG_USER.user_auth0_id
        , TCG_USER.firstname
        , TCG_USER.surname
        , TCG_USER.email
        , TCG_USER.is_email_verified
        , TCG_USER.is_super_user
        , TCG_USER.active
        , TCG_USER.created_on
        , TCG_USER.created_by_user_id
        , TCG_USER.updated_last_on
        , TCG_USER.updated_last_by_user_id
        , TCG_USER.change_set_id
    FROM tcg.public.TCG_User TCG_USER
    WHERE
            (
                (
                    NOT v_require_all_id_filters_met
                AND NOT v_require_any_id_filters_met
            )
            OR  (
                    v_require_all_id_filters_met
                AND (
                        v_get_all_user
                    OR  TCG_USER.user_id = ANY(string_to_array(v_user_ids, ',')::INT[])
                )
            )
            OR  (
                    NOT v_require_all_id_filters_met
                AND v_require_any_id_filters_met
                AND (
                        v_get_all_user
                    OR  TCG_USER.user_id = ANY(string_to_array(v_user_ids, ',')::INT[])
                )
            )
        )
        AND (
                v_get_inactive_user
            OR  TCG_USER.active
        )
	ORDER BY TCG_USER.firstname, TCG_USER.surname, TCG_USER.email
    ;
END;
$$;


SELECT *
FROM tcg.public.FN_TCG_User_Get_Many (
      a_get_all_user := TRUE
    , a_get_inactive_user := FALSE
    , a_user_ids := ''
    , a_require_all_id_filters_met := TRUE 
    , a_require_any_id_filters_met := FALSE 
)
;


SELECT *
FROM tcg.public.TCG_User
;
