-- Create Product Reviews Table
CREATE TABLE IF NOT EXISTS public.ml_product_reviews (
    id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
    user_id UUID NOT NULL REFERENCES auth.users(id),
    product_id UUID NOT NULL REFERENCES public.ml_products(id),
    order_id UUID NOT NULL REFERENCES public.ml_orders(id),
    order_item_id UUID, -- Optional: link to specific line item
    rating INTEGER CHECK (rating >= 1 AND rating <= 5),
    content TEXT,
    images JSONB DEFAULT '[]', -- Array of image URLs
    is_anonymous BOOLEAN DEFAULT false,
    reply TEXT, -- Merchant reply
    reply_time TIMESTAMPTZ,
    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW()
);

-- Create policies for product reviews
ALTER TABLE public.ml_product_reviews ENABLE ROW LEVEL SAFETY;

CREATE POLICY "Users can create reviews for their own orders" 
ON public.ml_product_reviews FOR INSERT 
TO authenticated 
WITH CHECK (auth.uid() = user_id);

CREATE POLICY "Users can view all reviews" 
ON public.ml_product_reviews FOR SELECT 
TO authenticated, anon 
USING (true);

-- Create Shop Reviews Table (if needed, or merge)
CREATE TABLE IF NOT EXISTS public.ml_shop_reviews (
    id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
    user_id UUID NOT NULL REFERENCES auth.users(id),
    shop_id UUID NOT NULL REFERENCES public.ml_shops(id), -- Assuming ml_shops exists
    order_id UUID NOT NULL REFERENCES public.ml_orders(id),
    description_rating INTEGER CHECK (description_rating >= 1 AND description_rating <= 5),
    logistics_rating INTEGER CHECK (logistics_rating >= 1 AND logistics_rating <= 5),
    service_rating INTEGER CHECK (service_rating >= 1 AND service_rating <= 5),
    created_at TIMESTAMPTZ DEFAULT NOW()
);

-- Create policies for shop reviews
ALTER TABLE public.ml_shop_reviews ENABLE ROW LEVEL SAFETY;

CREATE POLICY "Users can create shop reviews" 
ON public.ml_shop_reviews FOR INSERT 
TO authenticated 
WITH CHECK (auth.uid() = user_id);

CREATE POLICY "Anyone can view shop reviews" 
ON public.ml_shop_reviews FOR SELECT 
TO authenticated, anon 
USING (true);
