import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { getSessionClientId } from "@/lib/auth";
import { isAdminSession } from "@/lib/adminAuth";
import { connectDB } from "@/lib/db";
import { Client } from "@/models/Client";
import { corsHeaders, corsPreflight } from "@/lib/teamApiCors";

export async function OPTIONS(request: NextRequest) {
  return corsPreflight(request);
}

// Eigene, rein lesende Gehaltsansicht fürs Team-API/App-Pendant zu
// /account/mitarbeiter (MySalaryPanel) — bewusst KEIN team_management_view
// nötig, da es ausschließlich die eigenen Daten sind (gleiche Query wie
// AccountMitarbeiterPage, kein Umweg über getStaffFileData).
export async function GET(request: NextRequest) {
  const headers = corsHeaders(request);
  const clientId = await getSessionClientId();
  if (!clientId || !(await isAdminSession())) {
    return NextResponse.json({ error: "Nicht angemeldet." }, { status: 401, headers });
  }

  await connectDB();
  const client = await Client.findById(clientId).select("hourlyWage monthlyHours salaryHistory").lean();
  if (!client) return NextResponse.json({ error: "Nicht gefunden." }, { status: 404, headers });

  const salaryHistoryActors = await Client.find({ _id: { $in: (client.salaryHistory || []).map((h) => String(h.changedByClientId)) } })
    .select("name")
    .lean();
  const nameById = new Map(salaryHistoryActors.map((c) => [String(c._id), c.name]));

  return NextResponse.json(
    {
      hourlyWage: client.hourlyWage ?? null,
      monthlyHours: client.monthlyHours ?? null,
      salaryHistory: (client.salaryHistory || []).map((h) => ({
        id: String(h._id),
        oldHourlyWage: h.oldHourlyWage ?? null,
        newHourlyWage: h.newHourlyWage ?? null,
        reason: h.reason || "",
        byName: nameById.get(String(h.changedByClientId)) || "—",
        at: h.createdAt.toISOString(),
      })),
    },
    { headers }
  );
}
