import { NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { db } from "@/lib/db";

export async function GET() {
  const session = await auth();

  if (!session?.user?.id) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  try {
    const where = { userId: session.user.id };

    const [total, thumbsUpCount, thumbsDownCount, allFeedback] =
      await Promise.all([
        db.feedback.count({ where }),
        db.feedback.count({ where: { ...where, thumbsUp: true } }),
        db.feedback.count({ where: { ...where, thumbsUp: false } }),
        db.feedback.findMany({
          where: { ...where, rating: { not: null } },
          select: { rating: true },
        }),
      ]);

    // Calculate average rating from entries that have a rating
    const ratings = allFeedback
      .map((f) => f.rating)
      .filter((r): r is number => r !== null);
    const averageRating =
      ratings.length > 0
        ? ratings.reduce((sum, r) => sum + r, 0) / ratings.length
        : null;

    // Rating distribution (1-5)
    const ratingDistribution: Record<number, number> = { 1: 0, 2: 0, 3: 0, 4: 0, 5: 0 };
    for (const r of ratings) {
      ratingDistribution[r] = (ratingDistribution[r] || 0) + 1;
    }

    return NextResponse.json({
      total,
      thumbsUpCount,
      thumbsDownCount,
      averageRating: averageRating !== null ? Math.round(averageRating * 100) / 100 : null,
      ratedCount: ratings.length,
      ratingDistribution,
    });
  } catch {
    return NextResponse.json(
      { error: "Failed to fetch feedback stats" },
      { status: 500 }
    );
  }
}
