-- =============================================================================
-- P1: el bucket `menu` (fotos de productos/logos/portadas) permitia a CUALQUIER
-- autenticado borrar/pisar las fotos de OTRO negocio (ruta plana sin restaurante).
-- Ahora la ruta va {restaurante_id}/{carpeta}/{uuid} (frontend ya desplegado) y la
-- policy solo deja escribir/actualizar/borrar bajo la carpeta del PROPIO negocio.
-- La lectura publica (menu_lectura_publica) NO cambia: las fotos siguen visibles.
-- Los archivos viejos (logos/ portadas/ productos/) quedan legibles pero inmutables
-- (nadie los borra); el panel no borra fotos de menu, solo sube nuevas.
-- =============================================================================

drop policy if exists menu_escritura_auth on storage.objects;
create policy menu_escritura_auth on storage.objects for insert to authenticated
  with check (
    bucket_id = 'menu'
    and (storage.foldername(name))[1] = (select restaurante_id::text from public.perfiles where id = (select auth.uid()))
  );

drop policy if exists menu_update_auth on storage.objects;
create policy menu_update_auth on storage.objects for update to authenticated
  using (
    bucket_id = 'menu'
    and (storage.foldername(name))[1] = (select restaurante_id::text from public.perfiles where id = (select auth.uid()))
  )
  with check (
    bucket_id = 'menu'
    and (storage.foldername(name))[1] = (select restaurante_id::text from public.perfiles where id = (select auth.uid()))
  );

drop policy if exists menu_delete_auth on storage.objects;
create policy menu_delete_auth on storage.objects for delete to authenticated
  using (
    bucket_id = 'menu'
    and (storage.foldername(name))[1] = (select restaurante_id::text from public.perfiles where id = (select auth.uid()))
  );
