-- Ensure individuell orders persist net/vat components when total is manually set
-- and backfill existing records where these fields are still zero.

create or replace function public.sales_order_set_total(p_so_id uuid, p_total_eur integer)
returns void
language plpgsql
security invoker
as $$
declare
    v_so public.sales_orders;
    v_subtotal_eur integer := 0;
    v_vat_eur integer := 0;
begin
    select * into v_so from public.sales_orders where id = p_so_id for update;
    if not found then
        raise exception 'sales order % not found', p_so_id;
    end if;

    if v_so.rental_type != 'individuell' then
        raise exception 'can only set total for individuell orders';
    end if;

    if coalesce(p_total_eur, 0) < 0 then
        raise exception 'total must be >= 0';
    end if;

    if p_total_eur > 0 then
        v_subtotal_eur := round(p_total_eur / 1.2);
        v_vat_eur := p_total_eur - v_subtotal_eur;
    end if;

    update public.sales_orders
       set total_eur = p_total_eur,
           subtotal_eur = v_subtotal_eur,
           vat_eur = v_vat_eur,
           daily_subtotal = v_subtotal_eur,
           weekend_subtotal = 0,
           weekday_count = coalesce(total_days, 0),
           weekend_day_count = 0,
           updated_at = now()
     where id = p_so_id;
end;
$$;

grant execute on function public.sales_order_set_total(uuid, integer) to authenticated;

-- Backfill already existing individuell orders with missing net/vat split.
update public.sales_orders
   set subtotal_eur = round(total_eur / 1.2),
       vat_eur = total_eur - round(total_eur / 1.2),
       daily_subtotal = round(total_eur / 1.2),
       weekend_subtotal = 0,
       weekday_count = coalesce(total_days, 0),
       weekend_day_count = 0,
       updated_at = now()
 where rental_type = 'individuell'
   and coalesce(total_eur, 0) > 0
   and coalesce(subtotal_eur, 0) = 0
   and coalesce(vat_eur, 0) = 0;

notify pgrst, 'reload schema';
