import { prisma } from "@/lib/prisma";
import { requireUser, withGuard } from "@/lib/guard";
import { ok } from "@/lib/http";
import { progressPct } from "@/lib/utils";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

// GET /api/me — the signed-in user's personal performance summary.
// Dynamically matches User.position → PERSONAL KpiIndicators (FR-4).
export const GET = withGuard(async () => {
  const me = await requireUser();

  // Personal KPIs are shown for the current calendar month.
  const now = new Date();
  const year = now.getFullYear();
  const month = now.getMonth() + 1;

  const [user, tasks, personalKpis] = await Promise.all([
    prisma.user.findUnique({
      where: { id: me.id },
      select: {
        id: true,
        name: true,
        email: true,
        role: true,
        position: true,
        departmentId: true,
        department: { select: { id: true, name: true } },
      },
    }),
    prisma.task.findMany({
      where: { userId: me.id },
      include: { contributions: true },
      orderBy: { updatedAt: "desc" },
    }),
    // Personal KPIs assigned directly to this user (FR-2), plus any legacy
    // position-matched ones that were never reassigned to an individual.
    prisma.kpiIndicator.findMany({
      where: {
        type: "PERSONAL",
        OR: [
          { assignedUserId: me.id },
          ...(me.position
            ? [{ assignedUserId: null, assignedPosition: me.position }]
            : []),
        ],
      },
      include: { monthlyValues: { where: { year, month } } },
      orderBy: { name: "asc" },
    }),
  ]);

  const completed = tasks.filter((t) => t.status === "COMPLETED").length;
  const totalDelta = tasks.reduce(
    (sum, t) => sum + t.contributions.reduce((s, c) => s + c.metricDelta, 0),
    0
  );

  const kpis = personalKpis.map((k) => {
    // Use this month's values, falling back to the KPI's default target.
    const mv = k.monthlyValues[0];
    const target = mv?.targetValue ?? k.targetValue;
    const actual = mv?.actualValue ?? 0;
    return {
      id: k.id,
      name: k.name,
      description: k.description,
      unit: k.unit,
      period: k.period,
      targetValue: target,
      currentValue: actual,
      pct: progressPct(actual, target),
    };
  });

  return ok({
    user,
    stats: {
      tasksTotal: tasks.length,
      tasksCompleted: completed,
      inProgress: tasks.filter((t) => t.status === "IN_PROGRESS").length,
      totalDelta: Math.round(totalDelta * 100) / 100,
    },
    personalKpis: kpis,
  });
});
