import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { getSessionClientId } from "@/lib/auth";
import { isAdminSession } from "@/lib/adminAuth";
import { assignPhotoFolderAction } from "@/lib/actions/admin";
import { corsHeaders, corsPreflight } from "@/lib/teamApiCors";

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

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 targetClientId = typeof body?.clientId === "string" ? body.clientId : "";
  const nextcloudPath = typeof body?.nextcloudPath === "string" ? body.nextcloudPath : "";
  const label = typeof body?.label === "string" ? body.label : "";
  const assignedAt = typeof body?.assignedAt === "string" ? body.assignedAt : undefined;
  const orderId = typeof body?.orderId === "string" ? body.orderId : undefined;
  if (!targetClientId || !nextcloudPath) return NextResponse.json({ error: "Ordner fehlt." }, { status: 400, headers });

  await assignPhotoFolderAction(targetClientId, nextcloudPath, label || nextcloudPath, assignedAt, orderId);
  return NextResponse.json({ ok: true }, { headers });
}
