CREATE OR REPLACE VIEW medreport.user_accounts AS 
SELECT 
    account.id,
    account.name,
    account.picture_url,
    account.slug,
    membership.account_role AS role,
    COALESCE(account.application_role, 'user') AS application_role
FROM medreport.accounts account
JOIN medreport.accounts_memberships membership ON (account.id = membership.account_id)
WHERE (
    membership.user_id = (SELECT auth.uid())
    AND account.is_personal_account = false
    AND account.id IN (
        SELECT accounts_memberships.account_id
        FROM medreport.accounts_memberships
        WHERE accounts_memberships.user_id = (SELECT auth.uid())
    )
);

GRANT SELECT ON medreport.user_accounts TO authenticated, service_role;


DROP FUNCTION IF EXISTS medreport.team_account_workspace(text);

CREATE FUNCTION medreport.team_account_workspace(account_slug text)
 RETURNS TABLE(id uuid, name character varying, picture_url character varying, slug text, role character varying, role_hierarchy_level integer, primary_owner_user_id uuid, subscription_status medreport.subscription_status, permissions medreport.app_permissions[], application_role medreport.application_role)
 LANGUAGE plpgsql
 SET search_path TO ''
AS $function$begin
    return QUERY
    select
        accounts.id,
        accounts.name,
        accounts.picture_url,
        accounts.slug,
        accounts.application_role,
        accounts_memberships.account_role,
        roles.hierarchy_level,
        accounts.primary_owner_user_id,
        subscriptions.status,
        array_agg(role_permissions.permission)
    from
        medreport.accounts
        join medreport.accounts_memberships on accounts.id = accounts_memberships.account_id
        left join medreport.subscriptions on accounts.id = subscriptions.account_id
        join medreport.roles on accounts_memberships.account_role = roles.name
        left join medreport.role_permissions on accounts_memberships.account_role = role_permissions.role
    where
        accounts.slug = account_slug
        and medreport.accounts_memberships.user_id = (select auth.uid())
    group by
        accounts.id,
        accounts_memberships.account_role,
        subscriptions.status,
        roles.hierarchy_level;
end;$function$;

GRANT EXECUTE ON FUNCTION medreport.team_account_workspace(text) TO authenticated, service_role;

create or replace view medreport.user_account_workspace as SELECT accounts.id,
    accounts.name,
    accounts.picture_url,
    ( SELECT subscriptions.status
           FROM medreport.subscriptions
          WHERE (subscriptions.account_id = accounts.id)
         LIMIT 1) AS subscription_status,
    accounts.application_role
   FROM medreport.accounts
  WHERE ((accounts.primary_owner_user_id = ( SELECT auth.uid() AS uid)) AND (accounts.is_personal_account = true))
 LIMIT 1;

grant
    select
    on medreport.user_account_workspace to authenticated,
    service_role;
