-- 创建管理员AI助理聊天消息表
CREATE TABLE public.admin_chat_messages (
  id uuid NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
  user_id uuid NOT NULL,
  role text NOT NULL CHECK (role IN ('user', 'assistant')),
  content text NOT NULL,
  timestamp timestamp with time zone NOT NULL DEFAULT now(),
  actions jsonb,
  created_at timestamp with time zone NOT NULL DEFAULT now()
);

-- 启用RLS
ALTER TABLE public.admin_chat_messages ENABLE ROW LEVEL SECURITY;

-- 只有管理员可以查看管理员聊天记录
CREATE POLICY "Admins can view admin chat messages"
ON public.admin_chat_messages
FOR SELECT
USING (
  EXISTS (
    SELECT 1 FROM profiles
    WHERE profiles.user_id = auth.uid()
    AND profiles.role = 'admin'
  )
);

-- 只有管理员可以创建管理员聊天记录
CREATE POLICY "Admins can create admin chat messages"
ON public.admin_chat_messages
FOR INSERT
WITH CHECK (
  auth.uid() = user_id
  AND EXISTS (
    SELECT 1 FROM profiles
    WHERE profiles.user_id = auth.uid()
    AND profiles.role = 'admin'
  )
);

-- 创建索引以提高查询性能
CREATE INDEX idx_admin_chat_messages_user_id ON public.admin_chat_messages(user_id);
CREATE INDEX idx_admin_chat_messages_timestamp ON public.admin_chat_messages(timestamp DESC);