-- FUNCTION: sonex.current_account_preferences_update(text, text)

-- DROP FUNCTION IF EXISTS sonex.current_account_preferences_update(text, text);

CREATE OR REPLACE FUNCTION sonex.current_account_preferences_update(
	p_key text,
	p_value text)
    RETURNS boolean
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
AS $BODY$
DECLARE
    v_account_name text := session_user; -- aktualnie zalogowany użytkownik sesji
BEGIN
    IF p_key IS NULL OR btrim(p_key) = '' THEN
        RAISE EXCEPTION 'Preference key cannot be empty';
    END IF;

    INSERT INTO sonex.account_preferences (account_name, "key", "value", updated_at)
    VALUES (v_account_name, btrim(p_key), COALESCE(p_value, ''), now())
    ON CONFLICT (account_name, "key")
    DO UPDATE
    SET
        "value" = EXCLUDED."value",
        updated_at = now();

    RETURN true;
END;
$BODY$;

ALTER FUNCTION sonex.current_account_preferences_update(text, text)
    OWNER TO postgres;

GRANT EXECUTE ON FUNCTION sonex.current_account_preferences_update(text, text) TO account;

GRANT EXECUTE ON FUNCTION sonex.current_account_preferences_update(text, text) TO postgres;

REVOKE ALL ON FUNCTION sonex.current_account_preferences_update(text, text) FROM PUBLIC;
