import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { getSessionClientId } from "@/lib/auth";
import { isAdminSession, hasPermission } from "@/lib/adminAuth";
import { getClientList } from "@/lib/clientList";
import { adminCreateClientAction } 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) {
  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 { searchParams } = request.nextUrl;
  const result = await getClientList({
    q: searchParams.get("q") || "",
    page: Math.max(1, parseInt(searchParams.get("page") || "1", 10) || 1),
  });

  return NextResponse.json(result, { headers });
}

// "Konto vor Ort anlegen" — normales Kundenkonto, kein Mitarbeiterkonto
// (Berechtigungsprüfung steckt in adminCreateClientAction selbst: client_accounts).
export async function POST(request: NextRequest) {
  const headers = corsHeaders(request);
  const clientId = await getSessionClientId();
  if (!clientId || !(await isAdminSession())) {
    return NextResponse.json({ error: "Nicht angemeldet." }, { status: 401, headers });
  }
  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("nickname", typeof body?.nickname === "string" ? body.nickname : "");
  formData.set("email", typeof body?.email === "string" ? body.email : "");
  formData.set("password", typeof body?.password === "string" ? body.password : "");
  formData.set("birthDate", typeof body?.birthDate === "string" ? body.birthDate : "");
  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("locale", body?.locale === "en" ? "en" : "de");

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