import { getDb } from "../db.js";

function normalize(s) {
  return s.normalize("NFD").replace(/\p{Diacritic}/gu, "").toLowerCase();
}

export async function GET({ request }) {
  const q = new URL(request.url).searchParams.get("q")?.trim() || "";

  if (q.length < 2) {
    return new Response("[]", {
      headers: { "Content-Type": "application/json; charset=utf-8" },
    });
  }

  const db = getDb();

  const rows = db.prepare(`SELECT DISTINCT city FROM ranges`).all();

  const nq = normalize(q);

  const result = rows
    .filter((r) => normalize(r.city).includes(nq))
    .slice(0, 20)
    .map((r) => r.city);

  return new Response(JSON.stringify(result), {
    headers: { "Content-Type": "application/json; charset=utf-8" },
  });
}
