-- Faz 1: public read access needed by the customer-facing web renderer and
-- the QR stable-redirect route (PRD §9, §12). Menu/category/item public
-- policies already exist from the initial schema.
--
-- locations needs its own public policy first: the EXISTS subqueries below
-- (restaurants, restaurant_themes) and the web app's embedded join query
-- both read `locations` under the anon role, which is itself subject to RLS.

create policy "anyone can read locations with a published menu" on locations
  for select using (
    exists (
      select 1 from menus m where m.location_id = locations.id and m.is_published = true
    )
  );

create policy "anyone can read restaurants with a published menu" on restaurants
  for select using (
    exists (
      select 1
      from locations l
      join menus m on m.location_id = l.id
      where l.restaurant_id = restaurants.id and m.is_published = true
    )
  );

create policy "anyone can read theme of restaurants with a published menu" on restaurant_themes
  for select using (
    exists (
      select 1
      from locations l
      join menus m on m.location_id = l.id
      where l.restaurant_id = restaurant_themes.restaurant_id and m.is_published = true
    )
  );

-- target_url is a public destination URL, not sensitive — needed so the
-- unauthenticated /q/:id redirect route can resolve it.
create policy "anyone can read qr codes for redirect resolution" on qr_codes
  for select using (true);
