import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { getSessionClientId } from "@/lib/auth";
import { isAdminSession, hasPermission } from "@/lib/adminAuth";
import { getClientDetail } from "@/lib/clientDetail";
import { updateClientAccountAction, adminDeleteClientAction } from "@/lib/actions/clientAccounts";
import { corsHeaders, corsPreflight } from "@/lib/teamApiCors";

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

export async function GET(request: NextRequest, { params }: { params: Promise<{ clientId: string }> }) {
  const headers = corsHeaders(request);
  const clientId = await getSessionClientId();
  if (!clientId || !(await isAdminSession())) {
    return NextResponse.json({ error: "Nicht angemeldet." }, { status: 401, headers });
  }
  if (!(await hasPermission("clients_view"))) {
    return NextResponse.json({ error: "Keine Berechtigung." }, { status: 403, headers });
  }

  const { clientId: targetId } = await params;
  const detail = await getClientDetail(targetId);
  if (!detail) return NextResponse.json({ error: "Kunde nicht gefunden." }, { status: 404, headers });

  // Sicherheitslücke gefunden+geschlossen (25.09.2026): getClientDetail()
  // gibt den KOMPLETTEN Client-Dokument roh zurück (siehe clientDetail.ts) -
  // bei einem Mitarbeiter (role "staff") wären damit Gehalt/Gehalts-Historie/
  // Urlaubskontingent/Personalakte-Einträge über diese Route für JEDEN mit
  // der breiten "clients_view"-Berechtigung abrufbar gewesen, sobald die
  // clientId bekannt ist - unabhängig von der eigentlich dafür zuständigen,
  // viel engeren "team_management_view"-Berechtigung, die die Web-Oberfläche
  // (/admin/team/[clientId]) korrekt durchsetzt. Diese Route hier ist die
  // einzige Konsumentin von getClientDetail() (nur fürs Team-API/App gebaut),
  // hatte den Rollen-Check dabei aber schlicht vergessen.
  if (detail.client.role === "staff" && !(await hasPermission("team_management_view"))) {
    return NextResponse.json({ error: "Keine Berechtigung." }, { status: 403, headers });
  }
  // Verschlüsselte Felder nie als Ciphertext-Blob mitschicken, unabhängig von
  // der Berechtigung oben - dafür gibt es die dedizierte, eng gegatete
  // sensitiveData-Route mit eigenem Audit-Log (lib/actions/sensitiveData.ts).
  const { encryptedIban, encryptedSocialSecurityNumber, encryptedTaxId, ...clientWithoutSensitive } = detail.client;
  void encryptedIban;
  void encryptedSocialSecurityNumber;
  void encryptedTaxId;

  return NextResponse.json({ ...detail, client: clientWithoutSensitive }, { headers });
}

// Kundenstammdaten ändern — dieselbe enge client_accounts-Berechtigung wie im
// Web (Prüfung steckt schon in updateClientAccountAction selbst). Muss ALLE
// Felder forwarden, die die Action inzwischen erwartet (firstName/lastName/
// email sind dort Pflicht, salutation zusätzlich Pflicht für role==="client")
// — sonst schlägt jedes Speichern serverseitig fehl, auch wenn im App-Panel
// nur z. B. das Passwort geändert werden sollte.
export async function PATCH(request: NextRequest, { params }: { params: Promise<{ clientId: string }> }) {
  const headers = corsHeaders(request);
  const clientId = await getSessionClientId();
  if (!clientId || !(await isAdminSession())) {
    return NextResponse.json({ error: "Nicht angemeldet." }, { status: 401, headers });
  }
  const { clientId: targetId } = await params;
  const body = await request.json().catch(() => null);
  const formData = new FormData();
  formData.set("firstName", typeof body?.firstName === "string" ? body.firstName : "");
  formData.set("lastName", typeof body?.lastName === "string" ? body.lastName : "");
  formData.set("salutation", typeof body?.salutation === "string" ? body.salutation : "");
  formData.set("pronouns", typeof body?.pronouns === "string" ? body.pronouns : "");
  formData.set("nickname", typeof body?.nickname === "string" ? body.nickname : "");
  formData.set("email", typeof body?.email === "string" ? body.email : "");
  formData.set("phone", typeof body?.phone === "string" ? body.phone : "");
  formData.set("billingStreet", typeof body?.billingStreet === "string" ? body.billingStreet : "");
  formData.set("billingPostCode", typeof body?.billingPostCode === "string" ? body.billingPostCode : "");
  formData.set("billingCity", typeof body?.billingCity === "string" ? body.billingCity : "");
  formData.set("billingCountryCode", typeof body?.billingCountryCode === "string" && body.billingCountryCode ? body.billingCountryCode : "DE");
  formData.set("company", typeof body?.company === "string" ? body.company : "");
  if (typeof body?.password === "string" && body.password) formData.set("password", body.password);

  const result = await updateClientAccountAction(targetId, {}, formData);
  if (result.error) return NextResponse.json({ error: result.error }, { status: 400, headers });
  return NextResponse.json({ ok: true }, { headers });
}

export async function DELETE(request: NextRequest, { params }: { params: Promise<{ clientId: string }> }) {
  const headers = corsHeaders(request);
  const clientId = await getSessionClientId();
  if (!clientId || !(await isAdminSession())) {
    return NextResponse.json({ error: "Nicht angemeldet." }, { status: 401, headers });
  }
  const { clientId: targetId } = await params;
  const result = await adminDeleteClientAction(targetId);
  if (result.error) return NextResponse.json({ error: result.error }, { status: 400, headers });
  return NextResponse.json(result, { headers });
}
