-- Comprehensive fix for user RLS policies
-- Drop ALL existing policies and recreate them correctly

-- First, disable RLS temporarily to clear all policies
ALTER TABLE "public"."users" DISABLE ROW LEVEL SECURITY;

-- Re-enable RLS
ALTER TABLE "public"."users" ENABLE ROW LEVEL SECURITY;

-- Drop ALL existing policies (if they exist)
DROP POLICY IF EXISTS "Allow user insert for anon" ON "public"."users";
DROP POLICY IF EXISTS "Allow user insert for authenticated" ON "public"."users";
DROP POLICY IF EXISTS "Allow user insert for authenticator" ON "public"."users";
DROP POLICY IF EXISTS "Allow user insert for dashboard_user" ON "public"."users";
DROP POLICY IF EXISTS "Allow user profile creation during registration" ON "public"."users";
DROP POLICY IF EXISTS "Allow authenticated user profile creation" ON "public"."users";
DROP POLICY IF EXISTS "Allow user profile creation for service role" ON "public"."users";
DROP POLICY IF EXISTS "Users can view their own profile" ON "public"."users";
DROP POLICY IF EXISTS "Users can update their own profile" ON "public"."users";
DROP POLICY IF EXISTS "Users can view profiles in their organization" ON "public"."users";

-- Create comprehensive policies for all scenarios
-- 1. Allow anonymous users to create profiles during registration
CREATE POLICY "Allow user profile creation during registration" ON "public"."users" 
FOR INSERT TO "anon" WITH CHECK (true);

-- 2. Allow authenticated users to create their own profile
CREATE POLICY "Allow authenticated user profile creation" ON "public"."users" 
FOR INSERT TO "authenticated" WITH CHECK (auth.uid() = id);

-- 3. Allow service role to create user profiles
CREATE POLICY "Allow user profile creation for service role" ON "public"."users" 
FOR INSERT TO "service_role" WITH CHECK (true);

-- 4. Allow users to view their own profile
CREATE POLICY "Users can view their own profile" ON "public"."users" 
FOR SELECT TO "authenticated" USING (auth.uid() = id);

-- 5. Allow users to view profiles in their organization
CREATE POLICY "Users can view profiles in their organization" ON "public"."users" 
FOR SELECT TO "authenticated" USING (
  organization_id IN (
    SELECT organization_id FROM "public"."users" WHERE id = auth.uid()
  )
);

-- 6. Allow users to update their own profile
CREATE POLICY "Users can update their own profile" ON "public"."users" 
FOR UPDATE TO "authenticated" USING (auth.uid() = id);

-- 7. Allow service role to view all users
CREATE POLICY "Service role can view all users" ON "public"."users" 
FOR SELECT TO "service_role" USING (true);

-- 8. Allow service role to update all users
CREATE POLICY "Service role can update all users" ON "public"."users" 
FOR UPDATE TO "service_role" USING (true);

-- Refresh schema cache
NOTIFY pgrst, 'reload schema';
