-- Fix provider_services RLS policy to allow providers to insert their own services
-- The issue is that the INSERT policy checks profiles table but providers need access

-- Drop existing INSERT policy
DROP POLICY IF EXISTS "Providers can insert services" ON provider_services;

-- Create new INSERT policy that allows authenticated users to insert if they are providers
CREATE POLICY "Providers can insert their own services"
ON provider_services
FOR INSERT
TO public
WITH CHECK (
  auth.uid() = provider_id 
  AND EXISTS (
    SELECT 1 FROM profiles 
    WHERE profiles.id = auth.uid() 
    AND profiles.role IN ('provider', 'admin')
  )
);

-- Also ensure UPDATE policy uses auth.uid() for consistency
DROP POLICY IF EXISTS "Providers can update services" ON provider_services;

CREATE POLICY "Providers can update their own services"
ON provider_services
FOR UPDATE
TO public
USING (
  auth.uid() = provider_id 
  AND EXISTS (
    SELECT 1 FROM profiles 
    WHERE profiles.id = auth.uid() 
    AND profiles.role IN ('provider', 'admin')
  )
);

-- Add SELECT policy for providers to read their own services
DROP POLICY IF EXISTS "Providers can view their own services" ON provider_services;

CREATE POLICY "Providers can view their own services"
ON provider_services
FOR SELECT
TO public
USING (
  auth.uid() = provider_id 
  OR is_admin()
  OR true -- Public can view all (already exists as separate policy)
);