-- Optimize RLS policies to use (select auth.uid()) for better performance
-- This ensures auth.uid() is evaluated once per query, not once per row

-- Drop and recreate profiles policies
DROP POLICY IF EXISTS "Users can insert their own profile" ON public.profiles;
DROP POLICY IF EXISTS "Users can update their own profile" ON public.profiles;
DROP POLICY IF EXISTS "Users can delete their own profile" ON public.profiles;

CREATE POLICY "Users can insert their own profile"
  ON public.profiles FOR INSERT
  WITH CHECK ((select auth.uid()) = id);

CREATE POLICY "Users can update their own profile"
  ON public.profiles FOR UPDATE
  USING ((select auth.uid()) = id);

CREATE POLICY "Users can delete their own profile"
  ON public.profiles FOR DELETE
  USING ((select auth.uid()) = id);

-- Drop and recreate cars policies
DROP POLICY IF EXISTS "Owners can insert their own cars" ON public.cars;
DROP POLICY IF EXISTS "Owners can update their own cars" ON public.cars;
DROP POLICY IF EXISTS "Owners can delete their own cars" ON public.cars;

CREATE POLICY "Owners can insert their own cars"
  ON public.cars FOR INSERT
  WITH CHECK ((select auth.uid()) = owner_id);

CREATE POLICY "Owners can update their own cars"
  ON public.cars FOR UPDATE
  USING ((select auth.uid()) = owner_id);

CREATE POLICY "Owners can delete their own cars"
  ON public.cars FOR DELETE
  USING ((select auth.uid()) = owner_id);

-- Drop and recreate bookings policies
DROP POLICY IF EXISTS "Users can view their own bookings" ON public.bookings;
DROP POLICY IF EXISTS "Renters can create bookings" ON public.bookings;
DROP POLICY IF EXISTS "Owners can update booking status" ON public.bookings;
DROP POLICY IF EXISTS "Users can delete their own bookings" ON public.bookings;

CREATE POLICY "Users can view their own bookings"
  ON public.bookings FOR SELECT
  USING ((select auth.uid()) = renter_id OR (select auth.uid()) = owner_id);

CREATE POLICY "Renters can create bookings"
  ON public.bookings FOR INSERT
  WITH CHECK ((select auth.uid()) = renter_id);

CREATE POLICY "Owners can update booking status"
  ON public.bookings FOR UPDATE
  USING ((select auth.uid()) = owner_id OR (select auth.uid()) = renter_id);

CREATE POLICY "Users can delete their own bookings"
  ON public.bookings FOR DELETE
  USING ((select auth.uid()) = renter_id);
