-- ============================================
-- AutoMail Pro v6 — User Config Table
-- Colar e executar em: supabase.com → SQL Editor
-- (executar DEPOIS do supabase_setup.sql)
-- ============================================

-- Tabela de configurações por utilizador
CREATE TABLE IF NOT EXISTS user_config (
  id uuid DEFAULT gen_random_uuid() PRIMARY KEY,
  user_id uuid REFERENCES auth.users(id) ON DELETE CASCADE,
  config jsonb NOT NULL DEFAULT '{}',
  created_at timestamptz DEFAULT now(),
  updated_at timestamptz DEFAULT now(),
  UNIQUE(user_id)
);

-- RLS: cada user só vê/edita a sua config
ALTER TABLE user_config ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Users manage own config" ON user_config
  FOR ALL USING (auth.uid() = user_id) 
  WITH CHECK (auth.uid() = user_id);

-- Também atualizar RLS da tabela brands para permitir authenticated users
DROP POLICY IF EXISTS "Allow all operations" ON brands;
CREATE POLICY "Authenticated users manage brands" ON brands
  FOR ALL USING (auth.role() = 'authenticated' OR auth.role() = 'anon')
  WITH CHECK (auth.role() = 'authenticated' OR auth.role() = 'anon');
