import * as cheerio from "cheerio";
import { NextResponse } from "next/server";

export async function GET(req: Request) {
  if (req.method !== "GET") {
    return NextResponse.json({ error: "Method not allowed" });
  }
  try {
    const { searchParams } = new URL(req.url!);
    const url = searchParams.get("url");

    if (!url) {
      return NextResponse.json({
        success: false,
        error: "URL parameter is required",
      });
    }

    const response = await fetch(url, {
      headers: { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)" },
    });

    if (!response.ok) {
      return NextResponse.json({
        error: "Failed to fetch the URL",
        success: false,
      });
    }

    const html = await response.text();
    const $ = cheerio.load(html);

    // Extract metadata using cheerio
    const title = $("title").text() || "No title found";
    const description =
      $('meta[name="description"]').attr("content") ||
      $('meta[property="og:description"]').attr("content") ||
      "No description available";
    const image = $('meta[property="og:image"]').attr("content") || null;

    console.log(title, description, image);

    return NextResponse.json({
      success: true,
      url,
      meta: { title, description, image },
    });
  } catch (error) {
    console.error("Error fetching URL:", error);
    return NextResponse.json({
      error: "Failed to fetch URL metadata",
      success: false,
    });
  }
}
