import prisma from "../db.server";

// GET → fetch reviews
export const loader = async ({ request }) => {
  const url = new URL(request.url);
  const productId = url.searchParams.get("productId");

  if (!productId) {
    return new Response("Product ID missing", { status: 400 });
  }

  const reviews = await prisma.review.findMany({
    where: { productId },
    orderBy: { createdAt: "desc" },
  });

  return new Response(JSON.stringify(reviews), {
    headers: { "Content-Type": "application/json" },
  });
};

// POST → save review
export const action = async ({ request }) => {
  const formData = await request.formData();

  const name = formData.get("name");
  const review = formData.get("review");
  const productId = formData.get("productId");

  if (!productId) {
    return new Response("Product ID missing", { status: 400 });
  }

  await prisma.review.create({
    data: {
      productId,
      name,
      review,
    },
  });

  return new Response(JSON.stringify({ success: true }), {
    headers: { "Content-Type": "application/json" },
  });
};