import { NextResponse, type NextRequest } from "next/server";
import { aramaNormalize as normalize, eslesmePuani } from "@/lib/arama";
import { getAllBolumler, getAllUniversiteler } from "@/lib/katalog";
import { trBaslikDuzeni } from "@/lib/slug";

const SONUC_SINIRI = 6;

export function GET(request: NextRequest) {
  const hamSorgu = request.nextUrl.searchParams.get("q")?.trim() ?? "";
  const sorgu = normalize(hamSorgu).slice(0, 80);

  if (sorgu.length < 2) {
    return NextResponse.json({ bolumler: [], universiteler: [] });
  }

  const bolumler = getAllBolumler()
    .filter((bolum) => normalize(bolum.ad).includes(sorgu))
    .sort(
      (a, b) =>
        eslesmePuani(a.ad, sorgu) - eslesmePuani(b.ad, sorgu) ||
        b.programSayisi - a.programSayisi,
    )
    .slice(0, SONUC_SINIRI)
    .map((bolum) => ({
      href: `/bolum/${bolum.slug}`,
      ad: bolum.ad,
      programSayisi: bolum.programSayisi,
      enIyiSira: bolum.enIyiSira,
      seviye:
        bolum.lisans && bolum.onlisans
          ? "Lisans ve önlisans"
          : bolum.lisans
            ? "Lisans"
            : "Önlisans",
    }));

  const universiteler = getAllUniversiteler()
    .filter((universite) => normalize(universite.ad).includes(sorgu))
    .sort(
      (a, b) =>
        eslesmePuani(a.ad, sorgu) - eslesmePuani(b.ad, sorgu) ||
        b.programSayisi - a.programSayisi,
    )
    .slice(0, SONUC_SINIRI)
    .map((universite) => ({
      href: `/universite/${universite.slug}`,
      ad: universite.ad,
      il: universite.il ? trBaslikDuzeni(universite.il) : null,
      tur:
        universite.unitur === "DEVLET"
          ? "Devlet"
          : universite.unitur &&
              ["VAKIF", "VAKIF MYO"].includes(universite.unitur)
            ? "Vakıf"
            : universite.unitur
              ? "KKTC / Yurt dışı"
            : null,
      programSayisi: universite.programSayisi,
      fakulteSayisi: universite.fakulteSayisi,
    }));

  return NextResponse.json({ bolumler, universiteler });
}
