-- =====================
-- USER SETTINGS TABLE
-- (tambahkan setelah schema.sql)
-- =====================

CREATE TABLE IF NOT EXISTS user_settings (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  user_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE UNIQUE,

  -- AI Provider keys (disimpan di server, tidak pernah dikirim ke frontend)
  openai_api_key TEXT,
  anthropic_api_key TEXT,
  google_ai_api_key TEXT,

  -- Supabase config (untuk multi-tenant / user bawa sendiri)
  supabase_url TEXT,
  supabase_anon_key TEXT,

  -- Preferences
  preferred_ai_provider TEXT NOT NULL DEFAULT 'openai'
    CHECK (preferred_ai_provider IN ('openai', 'anthropic', 'google', 'auto')),
  preferred_model TEXT,
  default_language TEXT NOT NULL DEFAULT 'id'
    CHECK (default_language IN ('id', 'en')),
  default_mode TEXT NOT NULL DEFAULT 'simple'
    CHECK (default_mode IN ('simple', 'advanced')),
  default_variations INTEGER NOT NULL DEFAULT 1
    CHECK (default_variations IN (1, 3, 5)),

  -- Notification preferences
  email_notifications BOOLEAN NOT NULL DEFAULT TRUE,

  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- RLS
ALTER TABLE user_settings ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Users can view own settings"
  ON user_settings FOR SELECT USING (auth.uid() = user_id);

CREATE POLICY "Users can insert own settings"
  ON user_settings FOR INSERT WITH CHECK (auth.uid() = user_id);

CREATE POLICY "Users can update own settings"
  ON user_settings FOR UPDATE USING (auth.uid() = user_id);

-- Auto update timestamp
CREATE TRIGGER update_user_settings_updated_at
  BEFORE UPDATE ON user_settings
  FOR EACH ROW EXECUTE FUNCTION update_updated_at();

-- Auto-create empty settings on profile creation
CREATE OR REPLACE FUNCTION handle_new_user_settings()
RETURNS TRIGGER AS $$
BEGIN
  INSERT INTO user_settings (user_id)
  VALUES (NEW.id)
  ON CONFLICT (user_id) DO NOTHING;
  RETURN NEW;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;

CREATE OR REPLACE TRIGGER on_profile_created_create_settings
  AFTER INSERT ON profiles
  FOR EACH ROW EXECUTE FUNCTION handle_new_user_settings();

-- Index
CREATE INDEX idx_user_settings_user_id ON user_settings(user_id);
