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

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

export async function GET({ request }) {
  const url = new URL(request.url);

  const city = url.searchParams.get("city")?.trim() || "";
  const q = url.searchParams.get("q")?.trim() || "";

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

  const db = getDb();

  const rows = db
    .prepare(
      `SELECT DISTINCT street
       FROM ranges
       WHERE LOWER(city) = LOWER(?)
         AND TRIM(street) <> ''`
    )
    .all(city);

  const pattern = normalize(q);

  const filtered = rows
    .map((r) => r.street)
    .filter((street) => normalize(street).includes(pattern))
    .slice(0, 20);

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