// @ts-nocheck
import { Request, Response } from "express";
import asyncHandler from "../utils/asyncHandler";
import ApiError from "../utils/apiError";
import ApiResponse from "../utils/apiResponse";
import prisma from "../DB/db";

// --- Add Review ---
export const addReview = asyncHandler(async (req: Request, res: Response) => {
  const userId = req.user?.id;
  const { productId, rating, comment } = req.body;

  // 1. Check if user bought the product (Optional logic for Verified Purchase)
  /*
  const hasPurchased = await prisma.order.findFirst({
    where: {
      userId,
      status: "DELIVERED",
      items: { some: { productId } } // Check snapshots or relation
    }
  });
  if (!hasPurchased) throw new ApiError(false, 403, "You can only review purchased items");
  */

  // 2. Check for existing review
  const existingReview = await prisma.review.findFirst({
    where: { userId, productId },
  });

  if (existingReview) {
    throw new ApiError(false, 400, "You have already reviewed this product");
  }

  // 3. Create Review
  const review = await prisma.review.create({
    data: {
      userId: userId!,
      productId,
      rating: Number(rating),
      comment,
    },
  });

  return res.status(201).json(new ApiResponse(true, 201, "Review added", review));
});

// --- Get Product Reviews ---
export const getProductReviews = asyncHandler(async (req: Request, res: Response) => {
  const { productId } = req.params;

  const reviews = await prisma.review.findMany({
    where: { productId },
    include: {
      user: {
        select: { name: true, image: true }, // Only show name/avatar
      },
    },
    orderBy: { createdAt: "desc" },
  });

  return res.status(200).json(new ApiResponse(true, 200, "Reviews fetched", reviews));
});