-- ============================================================
-- Gustito Express — Cerrar el negocio: al cerrar, se borran los pedidos del dia
-- (y con ellos los datos personales del cliente). Privacidad por diseno.
-- El dueño descarga su reporte de ventas antes de cerrar.
-- ============================================================
create or replace function public.cerrar_negocio()
returns void language plpgsql security definer set search_path = public
as $$
declare v_rest uuid := fn_mi_restaurante();
begin
  if v_rest is null or not (fn_es_staff_de(v_rest) or fn_es_admin()) then
    raise exception 'Sin permiso';
  end if;
  update public.restaurantes set abierto = false where id = v_rest;
  -- borra pedidos + items + pagos (cascade) => desaparecen nombre/telefono/cedula/comprobante
  delete from public.pedidos where restaurante_id = v_rest;
  -- libera a los repartidores
  update public.repartidores set estado = 'disponible' where restaurante_id = v_rest and estado = 'ocupado';
end;
$$;
grant execute on function public.cerrar_negocio() to authenticated;
