-- =====================================================
-- SCRIPT COMPLETO PARA CORRIGIR PROBLEMAS DO SUPABASE
-- =====================================================

-- 1. CRIAR TABELA USERS SE NÃO EXISTIR
CREATE TABLE IF NOT EXISTS public.users (
  id UUID REFERENCES auth.users(id) PRIMARY KEY,
  name TEXT,
  email TEXT,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
  updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- 2. REMOVER TRIGGERS E FUNÇÕES ANTIGAS
DROP TRIGGER IF EXISTS on_auth_user_created ON auth.users;
DROP FUNCTION IF EXISTS public.handle_new_user();

-- 3. CRIAR FUNÇÃO DE TRIGGER CORRETA
CREATE OR REPLACE FUNCTION public.handle_new_user()
RETURNS TRIGGER AS $$
BEGIN
  INSERT INTO public.users (id, name, email)
  VALUES (
    NEW.id,
    COALESCE(NEW.raw_user_meta_data->>'name', 'User'),
    NEW.email
  );
  RETURN NEW;
EXCEPTION
  WHEN duplicate_key THEN
    -- User already exists, ignore
    RETURN NEW;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;

-- 4. CRIAR TRIGGER
CREATE TRIGGER on_auth_user_created
  AFTER INSERT ON auth.users
  FOR EACH ROW
  EXECUTE FUNCTION public.handle_new_user();

-- 5. DESABILITAR RLS PARA A TABELA USERS (TEMPORÁRIO)
ALTER TABLE public.users DISABLE ROW LEVEL SECURITY;

-- 6. DAR PERMISSÕES COMPLETAS PARA ANON E AUTHENTICATED
GRANT ALL ON public.users TO anon;
GRANT ALL ON public.users TO authenticated;
GRANT ALL ON public.users TO service_role;

-- 7. VERIFICAR ESTRUTURA DA TABELA
SELECT 
  column_name, 
  data_type, 
  is_nullable,
  column_default
FROM information_schema.columns 
WHERE table_name = 'users' 
  AND table_schema = 'public'
ORDER BY ordinal_position;

-- 8. VERIFICAR PERMISSÕES
SELECT 
  grantee,
  table_name,
  privilege_type
FROM information_schema.role_table_grants 
WHERE table_name = 'users' 
  AND table_schema = 'public';

-- 9. VERIFICAR TRIGGERS
SELECT 
  trigger_name,
  event_manipulation,
  action_timing,
  action_condition,
  action_statement
FROM information_schema.triggers 
WHERE event_object_table = 'users' 
  OR event_object_table = 'users';

-- 10. VERIFICAR FUNÇÕES
SELECT 
  proname,
  prosrc
FROM pg_proc 
WHERE proname = 'handle_new_user';
