DROP FUNCTION IF EXISTS medreport.get_benefits_usages_for_company_members(uuid);

CREATE OR REPLACE FUNCTION medreport.get_benefits_usages_for_company_members(p_account_id uuid)
returns table (
    personal_account_id uuid,
    benefit_amount numeric,
    benefit_unused_amount numeric
)
language plpgsql
as $$
begin
    return query
        with benefit_recipient_accounts as (
            -- Find all personal accounts that have received benefits from this company
            select distinct account_id
            from medreport.account_balance_entries
            where source_company_id = p_account_id
            and entry_type = 'benefit'
        )
        select
            bra.account_id as personal_account_id,
            coalesce(sum(case when abe.entry_type = 'benefit' and abe.source_company_id = p_account_id then abe.amount else 0 end), 0) as benefit_amount,
            coalesce(sum(case when abe.entry_type = 'benefit' and abe.source_company_id = p_account_id then abe.amount when abe.entry_type = 'purchase' then abe.amount else 0 end), 0) as benefit_unused_amount
        from benefit_recipient_accounts bra
        left join medreport.account_balance_entries abe on abe.account_id = bra.account_id
        group by bra.account_id;
end;
$$;

grant execute on function medreport.get_benefits_usages_for_company_members(uuid) to authenticated, service_role;
