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

/**
 * Server-side proxy for the live header's real search suggestions.
 *
 * The live template's `.search-input` hits a legacy Joomla frontend task,
 * `index.php?option=com_content&task=article.searchIndex`, not the REST v1
 * API — it's outside `/api/index.php/v1/`, so it needs Bearer auth like
 * nothing else here, just the same `webHost` cookie the rest of the site
 * uses. It returns a raw HTML `<li><a href="...">Title</a></li>` list.
 *
 * Its `href`s are rooted at the Joomla install's own path (this dev instance
 * lives under `/websites/`, e.g. `/websites/us/assignment-help-chicago`) —
 * stripped down to the app-relative route (`/us/assignment-help-chicago`)
 * the same way `joomlaService.siteBaseUrl` is derived, so results link
 * within this Next.js app rather than back out to the Joomla host.
 */

const JOOMLA_API_BASE_URL = process.env.JOOMLA_API_BASE_URL || "";
const siteBaseUrl = JOOMLA_API_BASE_URL.replace(/api\/index\.php\/v\d+\/?$/, "");
const siteBasePath = (() => {
  try {
    return new URL(siteBaseUrl).pathname.replace(/\/$/, "");
  } catch {
    return "";
  }
})();

export interface SearchResult {
  label: string;
  href: string;
}

const RESULT_RE = /<li[^>]*class="items"[^>]*><a\s+href="([^"]*)">([^<]*)<\/a><\/li>/g;

function parseResults(html: string): SearchResult[] {
  const results: SearchResult[] = [];
  for (const match of html.matchAll(RESULT_RE)) {
    let href = match[1].trim();
    if (siteBasePath && href.startsWith(siteBasePath)) {
      href = href.slice(siteBasePath.length) || "/";
    }
    results.push({ label: match[2].trim(), href });
  }
  return results;
}

export async function GET(request: NextRequest) {
  const query = request.nextUrl.searchParams.get("q")?.trim();
  if (!query) {
    return NextResponse.json({ results: [] });
  }

  const url = `${siteBaseUrl}index.php?option=com_content&task=article.searchIndex&site=${process.env.JOOMLA_SITE_COOKIE || "GAH"}&search=${encodeURIComponent(query)}`;

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

    const response = await fetch(url, {
      headers: { Cookie: `webHost=${process.env.JOOMLA_SITE_COOKIE || "GAH"}` },
      signal: controller.signal,
      cache: "no-store",
    });
    clearTimeout(timeout);

    if (!response.ok) {
      return NextResponse.json({ results: [] });
    }

    const html = await response.text();
    return NextResponse.json({ results: parseResults(html) });
  } catch {
    return NextResponse.json({ results: [] });
  }
}
