DROP FUNCTION IF EXISTS akuz.resource_quota_group_check() CASCADE;

CREATE OR REPLACE FUNCTION akuz.resource_quota_group_check()
RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
    IF EXISTS (
        SELECT 1
        FROM akuz.t_resource_quota q
        WHERE q.channel <> 5
          AND q.resourcequotaid = NEW.resourcequota
    ) THEN
        RAISE EXCEPTION USING
            MESSAGE = 'Квоту на группу можно установить только для канала Доктор.';
        RETURN NULL; 
    END IF;

    RETURN NEW;
END;
$$;

DROP TRIGGER IF EXISTS resource_quota_group_aftercheck ON akuz.t_resource_quota_group;

CREATE TRIGGER resource_quota_group_aftercheck
AFTER INSERT OR UPDATE
ON akuz.t_resource_quota_group
FOR EACH ROW
EXECUTE FUNCTION akuz.resource_quota_group_check();
