import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { getSessionClientId } from "@/lib/auth";
import { isAdminSession, hasPermission } from "@/lib/adminAuth";
import { listFolder, PHOTOGRAPHY_ROOT } from "@/lib/nextcloud";
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("orders_view")) && !(await hasPermission("clients_view"))) {
    return NextResponse.json({ error: "Keine Berechtigung." }, { status: 403, headers });
  }

  const path = request.nextUrl.searchParams.get("path") || PHOTOGRAPHY_ROOT;
  try {
    const entries = await listFolder(path);
    return NextResponse.json({ path, entries: entries.filter((e) => e.isDirectory) }, { headers });
  } catch (err) {
    return NextResponse.json({ error: err instanceof Error ? err.message : "Fehler" }, { status: 500, headers });
  }
}
