import { describe, it, expect } from "vitest";
import { filterAndCapCandidates } from "../candidates";
import type { Coordinates } from "../types";

const origin: Coordinates = { lat: 48.2079, lng: 15.6229 };

type Hit = { brigadeId: string; label: string };

describe("filterAndCapCandidates (reine Vorfilter-Logik)", () => {
  const coordsById = (m: Record<string, Coordinates | null>) =>
    (id: string): Coordinates | null => m[id] ?? null;

  it("filtert Wehren außerhalb des Radius heraus (ans Ende, nicht gelöscht)", () => {
    const hits: Hit[] = [
      { brigadeId: "nah", label: "nah" },
      { brigadeId: "fern", label: "fern" },
    ];
    const lookup = coordsById({
      nah: { lat: 48.21, lng: 15.63 }, // ~ wenige km
      fern: { lat: 48.2082, lng: 16.3738 }, // ~55 km > 10 km
    });
    const out = filterAndCapCandidates(origin, hits, lookup, 10, 100);
    // nah ist drin (Koordinaten + Radius), fern ans Ende verschoben
    expect(out[0]!.brigadeId).toBe("nah");
    expect(out[out.length - 1]!.brigadeId).toBe("fern");
  });

  it("kappt bei maxCandidates", () => {
    const hits: Hit[] = Array.from({ length: 10 }, (_, i) => ({
      brigadeId: `b${i}`,
      label: `b${i}`,
    }));
    const lookup = (): Coordinates => ({ lat: 48.21, lng: 15.63 });
    const out = filterAndCapCandidates(origin, hits, lookup, 60, 3);
    expect(out).toHaveLength(3);
  });

  it("Kandidaten ohne Koordinaten ans Ende, brigadeCoords=null", () => {
    const hits: Hit[] = [
      { brigadeId: "ohne", label: "ohne" },
      { brigadeId: "mit", label: "mit" },
    ];
    const lookup = coordsById({
      ohne: null,
      mit: { lat: 48.21, lng: 15.63 },
    });
    const out = filterAndCapCandidates(origin, hits, lookup, 60, 100);
    expect(out[0]!.brigadeId).toBe("mit");
    expect(out[0]!.brigadeCoords).not.toBeNull();
    expect(out[out.length - 1]!.brigadeId).toBe("ohne");
    expect(out[out.length - 1]!.brigadeCoords).toBeNull();
  });

  it("leere Trefferliste -> leeres Ergebnis", () => {
    const out = filterAndCapCandidates(origin, [], () => null, 60, 100);
    expect(out).toEqual([]);
  });
});
