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 });

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

// Unternehmen/Passwort ändern — dieselbe enge client_accounts-Berechtigung
// wie im Web (Prüfung steckt schon in updateClientAccountAction selbst).
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("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 });
}
