-- Drop existing restrictive policies
DROP POLICY IF EXISTS "Admins can view all provider services" ON provider_services;
DROP POLICY IF EXISTS "Providers can insert own services" ON provider_services;
DROP POLICY IF EXISTS "Providers can update own services" ON provider_services;
DROP POLICY IF EXISTS "Providers can view own services" ON provider_services;

-- Create more permissive policies for development with Clerk generic JWT
-- These policies check the provider role in profiles table instead of relying on auth.uid()

-- Allow providers to insert their own services (check that provider_id exists and has provider role)
CREATE POLICY "Providers can insert services" ON provider_services
  FOR INSERT TO public WITH CHECK (
    EXISTS (
      SELECT 1 FROM profiles 
      WHERE id = provider_id 
      AND role IN ('provider', 'admin')
    )
  );

-- Allow providers to update their own services (check that provider_id exists and has provider role)
CREATE POLICY "Providers can update services" ON provider_services
  FOR UPDATE TO public USING (
    EXISTS (
      SELECT 1 FROM profiles 
      WHERE id = provider_id 
      AND role IN ('provider', 'admin')
    )
  );

-- Allow anyone to view provider services (needed for public browsing)
CREATE POLICY "Public can view provider services" ON provider_services
  FOR SELECT TO public USING (true);

-- Allow admins to do everything
CREATE POLICY "Admins can manage all services" ON provider_services
  FOR ALL TO public USING (is_admin());
