-- FUNCTION: sonex.current_account_change_password(text)

-- DROP FUNCTION IF EXISTS sonex.current_account_change_password(text);

CREATE OR REPLACE FUNCTION sonex.current_account_change_password(
	p_new_password text)
    RETURNS boolean
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    SET search_path=sonex, pg_temp
AS $BODY$
DECLARE
    v_account_name text := current_user;
BEGIN
    p_new_password := btrim(coalesce(p_new_password, ''));

    IF p_new_password = '' THEN
        RAISE EXCEPTION 'Password cannot be empty';
    END IF;

    EXECUTE format(
        'ALTER ROLE CURRENT_USER PASSWORD %L',
        p_new_password
    );

    PERFORM sonex.system_logs_add(
        'accounts',
        'password_change_self',
        'account',
        NULL,
        v_account_name,
        jsonb_build_object(
            'pg_role_name', v_account_name
        ),
        'info',
        'permission_change_own_password'
    );

    RETURN true;
END;
$BODY$;

ALTER FUNCTION sonex.current_account_change_password(text)
    OWNER TO postgres;

GRANT EXECUTE ON FUNCTION sonex.current_account_change_password(text) TO permission_change_own_password;

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

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