-- Fix RLS policy for anonymous users to access their trips
-- The issue: NULL = NULL evaluates to NULL (not TRUE) in SQL
-- Solution: Use IS NOT DISTINCT FROM or explicit NULL checks

DROP POLICY IF EXISTS "Herkes public seyahatleri görebilir" ON trips;

CREATE POLICY "Herkes public seyahatleri görebilir"
  ON trips FOR SELECT
  USING (
    is_public = true 
    OR user_id IS NULL  -- Allow all anonymous trips
    OR auth.uid() = user_id  -- Allow users to see their own trips
  );

-- Also update trip_days policy to be more explicit
DROP POLICY IF EXISTS "Herkes seyahat günlerini yönetebilir" ON trip_days;

CREATE POLICY "Herkes seyahat günlerini yönetebilir"
  ON trip_days FOR ALL
  USING (
    EXISTS (
      SELECT 1 FROM trips 
      WHERE trips.id = trip_days.trip_id 
      AND (
        trips.is_public = true
        OR trips.user_id IS NULL  -- Allow all anonymous trips
        OR trips.user_id = auth.uid()  -- Allow users to manage their own trips
      )
    )
  );

-- Also update trip_places policy
DROP POLICY IF EXISTS "Herkes seyahat yerlerini yönetebilir" ON trip_places;

CREATE POLICY "Herkes seyahat yerlerini yönetebilir"
  ON trip_places FOR ALL
  USING (
    EXISTS (
      SELECT 1 FROM trip_days 
      JOIN trips ON trips.id = trip_days.trip_id 
      WHERE trip_days.id = trip_places.trip_day_id 
      AND (
        trips.is_public = true
        OR trips.user_id IS NULL  -- Allow all anonymous trips
        OR trips.user_id = auth.uid()  -- Allow users to manage their own trips
      )
    )
  );