import { Request, Response } from 'express';
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

// GET /api/admin/reviews
export const getReviews = async (req: Request, res: Response) => {
  try {
    const reviews = await prisma.review.findMany({
      include: {
        user: { select: { fullName: true, image: true } },
        product: { select: { name: true, images: true } },
      },
      orderBy: { createdAt: 'desc' },
      take: 50,
    });

    // Format data for easier consumption by frontend
    const formattedReviews = reviews.map((review) => ({
      id: review.id,
      user: review.user.fullName || 'Anonymous',
      userImage: review.user.image,
      product: review.product.name,
      rating: review.rating,
      comment: review.comment,
      reply: review.reply,
      status: review.status,
      date: review.createdAt.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }),
    }));

    res.json(formattedReviews);
  } catch (error) {
    console.error("Get Reviews Error:", error);
    res.status(500).json({ error: "Failed to fetch reviews" });
  }
};

// PUT /api/admin/reviews/:id/reply
export const replyToReview = async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const { reply } = req.body;

    if (!reply) return res.status(400).json({ error: "Reply content is required" });

    const updatedReview = await prisma.review.update({
      where: { id },
      data: { reply },
    });

    // TODO: Send email notification to user here via nodemailer

    res.json({ message: "Reply posted successfully", review: updatedReview });
  } catch (error) {
    console.error("Reply Review Error:", error);
    res.status(500).json({ error: "Failed to post reply" });
  }
};

// DELETE /api/admin/reviews/:id
export const deleteReview = async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    await prisma.review.delete({ where: { id } });
    res.json({ message: "Review deleted successfully" });
  } catch (error) {
    console.error("Delete Review Error:", error);
    res.status(500).json({ error: "Failed to delete review" });
  }
};