drop policy "Allow select and update if user is account's primary owner" on medreport.company_params;

create policy "Allow select and update if user is account's HR"
on medreport.company_params
for all
using (
    EXISTS (
    SELECT 1
    FROM medreport.accounts_memberships am
    WHERE am.account_id   = company_params.account_id
        AND am.user_id      = auth.uid()
        AND am.account_role = 'owner'
    )
)
with check (
    EXISTS (
    SELECT 1
    FROM medreport.accounts_memberships am
    WHERE am.account_id   = company_params.account_id
        AND am.user_id      = auth.uid()
        AND am.account_role = 'owner'
    )
);

create or replace function medreport.clear_benefit_amount_on_employee_deletion()
returns trigger
language plpgsql
security definer
set search_path = medreport, public
as $$
begin
  update medreport.account_balance_entries abe
     set amount = 0
   where abe.account_id = old.user_id
      AND abe.entry_type = 'benefit';

  return null;
end;
$$;

drop trigger if exists trigger_accounts_memberships_after_delete
  on medreport.accounts_memberships;

create trigger trigger_accounts_memberships_after_delete
after delete on medreport.accounts_memberships
for each row
execute function medreport.clear_benefit_amount_on_employee_deletion();
