import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { getSessionClientId } from "@/lib/auth";
import { isAdminSession } from "@/lib/adminAuth";
import { deleteBundleAction, updateBundleAction, moveBundleAction } from "@/lib/actions/bundles";
import { corsHeaders, corsPreflight } from "@/lib/teamApiCors";

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

export async function PATCH(request: NextRequest, { params }: { params: Promise<{ bundleId: string }> }) {
  const headers = corsHeaders(request);
  const clientId = await getSessionClientId();
  if (!clientId || !(await isAdminSession())) {
    return NextResponse.json({ error: "Nicht angemeldet." }, { status: 401, headers });
  }
  const { bundleId } = await params;
  const body = await request.json().catch(() => null);

  if (body?.direction === "up" || body?.direction === "down") {
    await moveBundleAction(bundleId, body.direction);
    return NextResponse.json({ ok: true }, { headers });
  }

  const formData = new FormData();
  formData.set("title", typeof body?.title === "string" ? body.title : "");
  formData.set("titleEn", typeof body?.titleEn === "string" ? body.titleEn : "");
  formData.set("description", typeof body?.description === "string" ? body.description : "");
  formData.set("descriptionEn", typeof body?.descriptionEn === "string" ? body.descriptionEn : "");
  formData.set("price", typeof body?.price === "number" ? String(body.price) : "0");
  if (body?.compareAtPrice) formData.set("compareAtPrice", String(body.compareAtPrice));
  await updateBundleAction(bundleId, formData);
  return NextResponse.json({ ok: true }, { headers });
}

export async function DELETE(request: NextRequest, { params }: { params: Promise<{ bundleId: string }> }) {
  const headers = corsHeaders(request);
  const clientId = await getSessionClientId();
  if (!clientId || !(await isAdminSession())) {
    return NextResponse.json({ error: "Nicht angemeldet." }, { status: 401, headers });
  }
  const { bundleId } = await params;
  await deleteBundleAction(bundleId);
  return NextResponse.json({ ok: true }, { headers });
}
