-- 创建售后申请表
CREATE TABLE public.after_sales_requests (
  id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
  user_id UUID NOT NULL,
  order_id UUID NOT NULL,
  product_id UUID NOT NULL,
  type TEXT NOT NULL CHECK (type IN ('return', 'exchange', 'repair')),
  status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'approved', 'processing', 'completed', 'rejected')),
  reason TEXT NOT NULL,
  description TEXT NOT NULL,
  images TEXT[],
  admin_notes TEXT,
  tracking_number TEXT,
  refund_amount NUMERIC(10,2),
  processed_by UUID,
  processed_at TIMESTAMP WITH TIME ZONE,
  created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
  updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now()
);

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

-- 创建RLS策略
CREATE POLICY "Users can view their own after sales requests" 
ON public.after_sales_requests 
FOR SELECT 
USING (auth.uid() = user_id);

CREATE POLICY "Users can create their own after sales requests" 
ON public.after_sales_requests 
FOR INSERT 
WITH CHECK (auth.uid() = user_id);

CREATE POLICY "Users can update their own after sales requests" 
ON public.after_sales_requests 
FOR UPDATE 
USING (auth.uid() = user_id);

CREATE POLICY "Admins can view all after sales requests" 
ON public.after_sales_requests 
FOR SELECT 
USING (EXISTS (
  SELECT 1 FROM profiles 
  WHERE profiles.user_id = auth.uid() 
  AND profiles.role = 'admin'
));

CREATE POLICY "Admins can update all after sales requests" 
ON public.after_sales_requests 
FOR UPDATE 
USING (EXISTS (
  SELECT 1 FROM profiles 
  WHERE profiles.user_id = auth.uid() 
  AND profiles.role = 'admin'
));

-- 创建更新时间戳的触发器
CREATE TRIGGER update_after_sales_requests_updated_at
BEFORE UPDATE ON public.after_sales_requests
FOR EACH ROW
EXECUTE FUNCTION public.update_updated_at_column();