import { NextRequest, NextResponse } from "next/server";

/**
 * Server-side proxy for the customer panel's real per-service deadline list.
 *
 * `calculator3.js`'s urgency-select handler POSTs to `api/get_urgency` and
 * injects the raw HTML `<option>`s it gets back — the same pattern as
 * `api/get_subjects` (see `app/api/subjects/route.ts`). This is the actual
 * source of the "Select Urgency" list; `calculator_constants.php`'s
 * `daySlice`/`hoursSlice` (vendored to `data/calculator-constants.json`) is
 * only the fallback `ServiceOrderForm.tsx` uses if this call fails, since the
 * panel is the live, authoritative source and the vendored file is a static
 * snapshot.
 *
 * Verified against the live endpoint: ids match the vendored constants
 * exactly (19 = 1 Day, 18 = 2 Days, 1 = 3 Days, ...), confirming the two
 * sources agree rather than one silently drifting from the other.
 */

const PANEL_URL = process.env.NEXT_PUBLIC_CPANEL_URL || "https://customerpanel.globalassignmenthelp.com";

export interface UrgencyOption {
  value: string;
  label: string;
}

// Real response shape: `<option   value="19"> 1 Day </option>` — no
// optgroups, no data attributes, just padded whitespace around the label.
const OPTION_RE = /<option\s+value="([^"]*)"\s*>([^<]*)<\/option>/g;

function parseUrgencyHtml(html: string): UrgencyOption[] {
  const options: UrgencyOption[] = [];
  for (const match of html.matchAll(OPTION_RE)) {
    const value = match[1].trim();
    if (!value) continue; // skip the "-- Select Urgency --" placeholder
    options.push({ value, label: match[2].trim() });
  }
  return options;
}

export async function POST(request: NextRequest) {
  const { assignmentId } = await request.json();

  if (!assignmentId) {
    return NextResponse.json({ error: "assignmentId is required" }, { status: 400 });
  }

  const body = new URLSearchParams({
    assignment_id: String(assignmentId),
    urgency: "",
    type: "web",
  });

  try {
    const controller = new AbortController();
    const timeout = setTimeout(() => controller.abort(), 8000);

    const response = await fetch(`${PANEL_URL}/api/get_urgency`, {
      method: "POST",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      body,
      signal: controller.signal,
      cache: "no-store",
    });
    clearTimeout(timeout);

    if (!response.ok) {
      return NextResponse.json({ error: "Panel returned an error" }, { status: 502 });
    }

    const html = await response.text();
    return NextResponse.json({ urgencies: parseUrgencyHtml(html) });
  } catch {
    return NextResponse.json({ error: "Urgency service unreachable" }, { status: 504 });
  }
}
