create type "medreport"."application_role" as enum ('user', 'doctor', 'super_admin');

ALTER TABLE medreport.accounts
ADD COLUMN "application_role" medreport.application_role NOT NULL DEFAULT 'user';

CREATE OR REPLACE FUNCTION medreport.is_doctor()
RETURNS BOOLEAN
LANGUAGE plpgsql
SECURITY DEFINER
AS $$
BEGIN
  RETURN medreport.is_aal2() AND (EXISTS (
    SELECT 1 
    FROM medreport.accounts 
    WHERE primary_owner_user_id = auth.uid() 
    AND application_role = 'doctor'
  ));
END;
$$;
grant execute on function medreport.is_doctor() to authenticated;


CREATE OR REPLACE FUNCTION medreport.is_super_admin()
RETURNS BOOLEAN
LANGUAGE plpgsql
SECURITY DEFINER
AS $$
BEGIN
  RETURN medreport.is_aal2() AND (EXISTS (
    SELECT 1 
    FROM medreport.accounts 
    WHERE primary_owner_user_id = auth.uid() 
    AND application_role = 'super_admin'
  ));
END;
$$;
grant execute on function medreport.is_super_admin() to authenticated;