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

/**
 * Server-side proxy for the customer panel's price calculator.
 *
 * The live site calls this endpoint directly from the browser
 * (`calculator3.js`'s `price_calculater_order()`, which POSTs to
 * `api/price_calculateNew`). Going through a route handler instead keeps it
 * same-origin — the panel sets no CORS headers for this app.
 *
 * Uses `price_calculateNew`, not the older `price_calculate` this route used
 * before — the New endpoint additionally takes `addonprice`, a per-subject
 * surcharge that materially changes the price (verified live: addonprice
 * 10000 moved a $5.66 quote to $122.66). Without it every quote was missing
 * whatever the visitor's subject choice adds.
 *
 * Verified parameter behaviour (probed against the live endpoint):
 * - `assignment_id` selects the service (8 → 4.24, 33 → 5.66, 13 → 7.93) —
 *   `JM_assignment_web` ids.
 * - `page` scales it (1 → 5.66, 10 → 57.47).
 * - `urgency` is a slice id from `calculator_constants.php`
 *   (19 = 0–1 day → 9.75, 8 = 25–30 days → 5.66, 13 = 50–55 days → 5.35).
 * - `addonprice` is the selected subject's surcharge — see `app/api/subjects`.
 * - `currencies` had no effect on the response; the panel always answers in
 *   USD, and the template converts client-side by multiplying by the
 *   country's `currency_value`.
 */

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

export interface PriceQuote {
  /** Discounted price, in USD, before per-country conversion. */
  totalPrice: number;
  /** Pre-discount price, same basis. */
  totalPriceBeforeDiscount: number;
  /** Words the quote covers, e.g. 250 per page. */
  words: number;
  /** `res.discountPrice` — the discount amount, USD. */
  discountPrice: number;
}

export async function POST(request: NextRequest) {
  const {
    assignmentId,
    page,
    urgency,
    serviceGroupId,
    addonPrice,
    serviceName,
    words: wordsOverride,
  } = await request.json();

  if (!assignmentId || !page || !urgency) {
    return NextResponse.json(
      { error: "assignmentId, page and urgency are required" },
      { status: 400 }
    );
  }

  // `filewords`/`words` is normally page count * 250 words/page, but
  // Editing | Proofreading and Plagiarism Report post an explicit word count
  // instead (`calculator3.js`'s `d_service == 'Editing | Proofreading' ...`
  // branch) since those services aren't priced by page.
  const words = wordsOverride || page * 250;
  const body = new URLSearchParams({
    assignment_id: String(assignmentId),
    currencies: "1",
    filewords: String(words),
    ser_adv_op: "Basic",
    site_name: BRAND,
    display_service: serviceName || "",
    page: String(page),
    words: String(words),
    addonprice: String(addonPrice ?? 0),
    urgency: String(urgency),
    service_group_id: String(serviceGroupId ?? assignmentId),
    type: "web",
  });

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

    const response = await fetch(`${PANEL_URL}/api/price_calculateNew`, {
      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 data = await response.json();
    const quote: PriceQuote = {
      totalPrice: Number(data.totalprice) || 0,
      totalPriceBeforeDiscount: Number(data.totalprice_custom) || 0,
      words: Number(data.words) || 0,
      discountPrice: Number(data.discountPrice) || 0,
    };
    return NextResponse.json(quote);
  } catch {
    return NextResponse.json({ error: "Price service unreachable" }, { status: 504 });
  }
}
