-- Fix upsert function and RLS permissions
-- Run this to fix the ON CONFLICT error and 403 permission error

-- 1. Fix the upsert function to not use ON CONFLICT
create or replace function medreport.upsert_benefit_distribution_schedule(
    p_company_id uuid,
    p_benefit_amount numeric,
    p_benefit_occurrence text
)
returns void
language plpgsql
as $$
declare
    next_distribution_date timestamp with time zone;
    existing_record_id uuid;
begin
    -- Calculate next distribution date
    next_distribution_date := medreport.calculate_next_distribution_date(p_benefit_occurrence);
    
    -- Check if there's an existing record for this company
    select id into existing_record_id
    from medreport.benefit_distribution_schedule
    where company_id = p_company_id
    limit 1;
    
    if existing_record_id is not null then
        -- Update existing record
        update medreport.benefit_distribution_schedule
        set 
            benefit_amount = p_benefit_amount,
            benefit_occurrence = p_benefit_occurrence,
            next_distribution_at = next_distribution_date,
            is_active = true,
            updated_at = now()
        where id = existing_record_id;
    else
        -- Insert new record
        insert into medreport.benefit_distribution_schedule (
            company_id,
            benefit_amount,
            benefit_occurrence,
            next_distribution_at
        ) values (
            p_company_id,
            p_benefit_amount,
            p_benefit_occurrence,
            next_distribution_date
        );
    end if;
end;
$$;

-- 2. Grant permissions to authenticated users
grant select, insert, update, delete on table "medreport"."benefit_distribution_schedule" to authenticated;
