import { NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import {
  buildCategoryBreakdown,
  canAccessExperienciometro,
  ensureExperienceBaseline,
  getPublishedExperienceTemplate,
  mapExperienceEvaluation,
  mapExperienceFinding,
  mapExperienceTemplate,
  mapLocationSummary,
} from "@/lib/experienciometro";

export async function GET(_request: Request, context: { params: { id: string } }) {
  const session = await getServerSession(authOptions);
  if (!session?.user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  if (!canAccessExperienciometro(session.user.role)) {
    return NextResponse.json({ error: "Forbidden" }, { status: 403 });
  }

  await ensureExperienceBaseline(prisma, session.user.id);

  const locationId = context.params.id;

  const [locationRaw, templateRaw, evaluationsRaw, findingsRaw] = await Promise.all([
    prisma.location.findFirst({
      where: {
        id: locationId,
        isActive: true,
      },
      include: {
        managerUser: {
          select: {
            name: true,
            email: true,
          },
        },
        metrics: {
          select: {
            currentScore: true,
            signal: true,
            trendDelta: true,
            trendDirection: true,
            lastEvaluationAt: true,
            totalEvaluations: true,
            openFindings: true,
          },
        },
      },
    }),
    getPublishedExperienceTemplate(prisma),
    prisma.experienceEvaluation.findMany({
      where: { locationId },
      include: {
        createdBy: {
          select: {
            name: true,
            email: true,
          },
        },
        responses: {
          orderBy: [{ createdAt: "asc" }],
        },
      },
      orderBy: [{ evaluatedAt: "desc" }, { createdAt: "desc" }],
      take: 40,
    }),
    prisma.experienceFinding.findMany({
      where: { locationId },
      include: {
        responsibleUser: {
          select: {
            name: true,
            email: true,
          },
        },
        createdBy: {
          select: {
            name: true,
            email: true,
          },
        },
      },
      orderBy: [{ createdAt: "desc" }],
      take: 80,
    }),
  ]);

  if (!locationRaw) {
    return NextResponse.json({ error: "Location not found." }, { status: 404 });
  }

  const location = mapLocationSummary(locationRaw);
  const template = templateRaw ? mapExperienceTemplate(templateRaw) : null;
  const evaluations = evaluationsRaw.map(mapExperienceEvaluation);
  const findings = findingsRaw.map(mapExperienceFinding);

  const categoryBreakdown = buildCategoryBreakdown(evaluationsRaw);
  const trend = evaluations
    .slice()
    .reverse()
    .map((evaluation) => ({
      evaluationId: evaluation.id,
      evaluatedAt: evaluation.evaluatedAt,
      score: evaluation.totalScore,
    }));

  return NextResponse.json({
    ok: true,
    location,
    template,
    evaluations,
    categoryBreakdown,
    trend,
    findings,
  });
}
