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

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

export async function PATCH(request: NextRequest, { params }: { params: Promise<{ codeId: string }> }) {
  const headers = corsHeaders(request);
  const clientId = await getSessionClientId();
  if (!clientId || !(await isAdminSession())) {
    return NextResponse.json({ error: "Nicht angemeldet." }, { status: 401, headers });
  }
  const { codeId } = await params;
  const body = await request.json().catch(() => null);
  const formData = new FormData();
  formData.set("type", body?.type === "fixed" ? "fixed" : "percent");
  formData.set("value", typeof body?.value === "number" ? String(body.value) : "0");
  if (body?.maxUses) formData.set("maxUses", String(body.maxUses));
  if (body?.validUntil) formData.set("validUntil", body.validUntil);
  if (body?.note) formData.set("note", body.note);
  if (body?.stammkundenOnly) formData.set("stammkundenOnly", "on");
  if (body?.neukundenOnly) formData.set("neukundenOnly", "on");
  if (body?.conventionId) formData.set("conventionId", body.conventionId);

  await updateDiscountCodeAction(codeId, formData);
  return NextResponse.json({ ok: true }, { headers });
}

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