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

export async function GET(request: NextRequest) {
  const username = request.nextUrl.searchParams.get("username")?.trim();
  if (!username) {
    return NextResponse.json({ valid: false, error: "No username" });
  }

  try {
    const res = await fetch(`https://www.instagram.com/${username}/`, {
      method: "HEAD",
      redirect: "follow",
      headers: {
        "User-Agent":
          "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
      },
      signal: AbortSignal.timeout(5000),
    });

    // Instagram returns 200 for existing profiles, 404 for non-existing
    const valid = res.ok;
    return NextResponse.json({ valid });
  } catch {
    // Network error or timeout — don't block the user
    return NextResponse.json({ valid: true, uncertain: true });
  }
}
