import { NextResponse } from "next/server";
import { load } from "cheerio";

export const revalidate = 3600; // cache for 1 hour

export async function GET() {
  try {
    const res = await fetch("https://www.openpowerlifting.org/mlist/apportugal", {
      headers: { "User-Agent": "APP-Website/1.0" },
      next: { revalidate },
    });
    const html = await res.text();
    const $ = load(html);
    const meets: { id: string; name: string; href: string; date?: string; location?: string }[] = [];
    $("a").each((_, el) => {
      const href = $(el).attr("href") || "";
      const text = $(el).text().trim();
      const match = href.match(/\/m\/apportugal\/(\d+)/);
      if (match) {
        meets.push({ id: match[1], name: text, href });
      }
    });
    return NextResponse.json({ meets });
  } catch (e) {
    return NextResponse.json({ error: "Failed to scrape meets" }, { status: 500 });
  }
}
