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[],
    account_role varchar,
    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,
        roles.name,
        roles.hierarchy_level,
        accounts.primary_owner_user_id,
        subscriptions.status,
        array_agg(role_permissions.permission),
        accounts_memberships.account_role,
        accounts.application_role
    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,
        roles.name;
end;$function$;

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