
CREATE TABLE public.ai_provider_configs (
  id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
  purpose TEXT NOT NULL UNIQUE,
  provider TEXT NOT NULL DEFAULT 'lovable',
  model TEXT NOT NULL,
  extra JSONB NOT NULL DEFAULT '{}'::jsonb,
  enabled BOOLEAN NOT NULL DEFAULT true,
  description TEXT,
  updated_by UUID,
  created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
  updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now()
);

ALTER TABLE public.ai_provider_configs ENABLE ROW LEVEL SECURITY;

CREATE POLICY "ai_provider_configs_select_all"
ON public.ai_provider_configs FOR SELECT
USING (true);

CREATE POLICY "ai_provider_configs_admin_insert"
ON public.ai_provider_configs FOR INSERT
TO authenticated
WITH CHECK (public.is_admin(auth.uid()));

CREATE POLICY "ai_provider_configs_admin_update"
ON public.ai_provider_configs FOR UPDATE
TO authenticated
USING (public.is_admin(auth.uid()))
WITH CHECK (public.is_admin(auth.uid()));

CREATE POLICY "ai_provider_configs_admin_delete"
ON public.ai_provider_configs FOR DELETE
TO authenticated
USING (public.is_admin(auth.uid()));

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

INSERT INTO public.ai_provider_configs (purpose, provider, model, description) VALUES
  ('default', 'lovable', 'google/gemini-2.5-flash', '全局默认文本模型'),
  ('product_description', 'lovable', 'google/gemini-2.5-flash', '商品描述生成'),
  ('product_image', 'lovable', 'google/gemini-2.5-flash-image', '商品图生成');
