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

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 body = await request.json().catch(() => null);
  const formData = new FormData();
  formData.set("amount", typeof body?.amount === "number" ? String(body.amount) : "0");
  formData.set("purchaserName", typeof body?.purchaserName === "string" ? body.purchaserName : "");
  formData.set("purchaserEmail", typeof body?.purchaserEmail === "string" ? body.purchaserEmail : "");
  formData.set("recipientName", typeof body?.recipientName === "string" ? body.recipientName : "");
  formData.set("message", typeof body?.message === "string" ? body.message : "");
  // Default an (anders als leeres Feld = "nicht angekreuzt" bei einer echten
  // Checkbox) — sonst bekäme jeder über die App ausgestellte Gutschein
  // stillschweigend nie die Code-Mail, anders als im Web-Formular (dort
  // startet die Checkbox angehakt).
  if (body?.sendEmail !== false) formData.set("sendEmail", "on");

  const result = await adminIssueVoucherAction({}, formData);
  if (result.error) return NextResponse.json({ error: result.error }, { status: 400, headers });
  return NextResponse.json({ ok: true }, { headers });
}
