import { queryFeaturesByIds } from "@/utils/mapQueryService";
import {
  clearPipeDiameterCache,
  getPipeDiameterDisplay,
  loadPipeDiameters,
} from "./schemePipeDiameters";

jest.mock("@/utils/mapQueryService", () => ({
  queryFeaturesByIds: jest.fn(),
}));

const feature = (id: string, diameter: number) => ({
  getProperties: () => ({ id, diameter }),
});

afterEach(() => {
  clearPipeDiameterCache();
  jest.clearAllMocks();
});

describe("loadPipeDiameters", () => {
  it("shares an in-flight WFS request and reuses its resolved result", async () => {
    let resolveFeatures: ((features: ReturnType<typeof feature>[]) => void) | undefined;
    const pendingFeatures = new Promise<ReturnType<typeof feature>[]>((resolve) => {
      resolveFeatures = resolve;
    });
    (queryFeaturesByIds as jest.Mock).mockImplementation(
      async () => pendingFeatures,
    );

    const firstRequest = loadPipeDiameters(["P-1"]);
    const duplicateRequest = loadPipeDiameters(["P-1"]);

    expect(queryFeaturesByIds).toHaveBeenCalledTimes(1);

    resolveFeatures?.([feature("P-1", 315)]);
    await expect(firstRequest).resolves.toEqual({ "P-1": 315 });
    await expect(duplicateRequest).resolves.toEqual({ "P-1": 315 });

    await expect(loadPipeDiameters(["P-1"])).resolves.toEqual({
      "P-1": 315,
    });
    expect(queryFeaturesByIds).toHaveBeenCalledTimes(1);
  });
});

describe("getPipeDiameterDisplay", () => {
  it("shows the actual diameter for one burst pipe", () => {
    expect(getPipeDiameterDisplay(["P-1"], { "P-1": 315 })).toBe("315 mm");
  });

  it("shows pipe IDs with diameters for multiple burst pipes", () => {
    expect(
      getPipeDiameterDisplay(["P-1", "P-2"], {
        "P-1": 315,
        "P-2": 800,
      }),
    ).toBe("P-1: 315 mm；P-2: 800 mm");
  });

  it("does not fall back to a fixed diameter when a diameter is missing", () => {
    expect(getPipeDiameterDisplay(["P-1"], {})).toBe("N/A");
  });
});
