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

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

export async function GET(request: NextRequest, { params }: { params: Promise<{ folderId: string }> }) {
  const headers = corsHeaders(request);
  const clientId = await getSessionClientId();
  if (!clientId || !(await isAdminSession()) || !(await hasPermission("orders_view"))) {
    return NextResponse.json({ error: "Nicht angemeldet." }, { status: 401, headers });
  }
  const { folderId } = await params;
  const detail = await getPhotoFolderDetail(folderId);
  if (!detail) return NextResponse.json({ error: "Ordner nicht gefunden." }, { status: 404, headers });
  return NextResponse.json(detail, { headers });
}

// Freigabe pro Foto (einzeln oder "alle") — das eigentliche Ordner-Freigeben
// (released) läuft weiterhin über /photo-folders/[folderId].
export async function POST(request: NextRequest, { params }: { params: Promise<{ folderId: string }> }) {
  const headers = corsHeaders(request);
  const clientId = await getSessionClientId();
  if (!clientId || !(await isAdminSession())) {
    return NextResponse.json({ error: "Nicht angemeldet." }, { status: 401, headers });
  }
  const { folderId } = await params;
  const body = await request.json().catch(() => null);
  const targetClientId = typeof body?.clientId === "string" ? body.clientId : "";
  if (!targetClientId) return NextResponse.json({ error: "Kunde fehlt." }, { status: 400, headers });

  if (Array.isArray(body?.fileNames)) {
    await approveAllPhotosAction(folderId, targetClientId, body.fileNames.filter((f: unknown) => typeof f === "string"));
    return NextResponse.json({ ok: true }, { headers });
  }

  const fileName = typeof body?.fileName === "string" ? body.fileName : "";
  const approved = Boolean(body?.approved);
  if (!fileName) return NextResponse.json({ error: "Datei fehlt." }, { status: 400, headers });
  await setPhotoApprovalAction(folderId, targetClientId, fileName, approved);
  return NextResponse.json({ ok: true }, { headers });
}
