import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { getSessionClientId } from "@/lib/auth";
import { isAdminSession, hasPermission } from "@/lib/adminAuth";
import { getReviews } from "@/lib/reviewList";
import { createTestimonialAction } from "@/lib/actions/testimonials";
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("testimonials_view"))) {
    return NextResponse.json({ error: "Keine Berechtigung." }, { status: 403, headers });
  }
  const data = await getReviews();
  return NextResponse.json(data, { headers });
}

// Multipart direkt durchgereicht (inkl. optionalem Bild) — dieselben
// Feldnamen wie NewTestimonialForm im Browser.
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 formData = await request.formData();
  const result = await createTestimonialAction({}, formData);
  if (result.error) return NextResponse.json({ error: result.error }, { status: 400, headers });
  return NextResponse.json({ ok: true }, { headers });
}
