
CREATE TABLE public.chatbot_configs (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id uuid NOT NULL,
  name text NOT NULL,
  welcome_message text NOT NULL DEFAULT 'Hello! How can I help you today?',
  system_prompt text NOT NULL DEFAULT 'You are a helpful, concise customer support assistant.',
  brand_color text NOT NULL DEFAULT '#7c3aed',
  is_active boolean NOT NULL DEFAULT true,
  created_at timestamptz NOT NULL DEFAULT now(),
  updated_at timestamptz NOT NULL DEFAULT now()
);

GRANT SELECT ON public.chatbot_configs TO anon;
GRANT SELECT, INSERT, UPDATE, DELETE ON public.chatbot_configs TO authenticated;
GRANT ALL ON public.chatbot_configs TO service_role;

ALTER TABLE public.chatbot_configs ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Public can read active chatbots"
  ON public.chatbot_configs FOR SELECT
  TO anon, authenticated
  USING (is_active = true);

CREATE POLICY "Owners manage their chatbots"
  ON public.chatbot_configs FOR ALL
  TO authenticated
  USING (auth.uid() = user_id)
  WITH CHECK (auth.uid() = user_id);

CREATE TRIGGER trg_chatbot_configs_updated_at
  BEFORE UPDATE ON public.chatbot_configs
  FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column();
