import { describe, expect, it } from "vitest";
import {
  DYNAMIC_SEGMENT_TOKEN,
  dedupeTargets,
  findMatchingApiRouteEntry,
  findMatchingRouteValue,
  modulePathKey,
  pageLabelFromRoute,
  routePatternMatchesCandidate,
  toApiRequestPath,
  toSelectionType,
} from "./shared.mjs";

describe("coverage shared helpers", () => {
  it("builds readable page labels from routes", () => {
    expect(pageLabelFromRoute("/")).toBe("Home");
    expect(pageLabelFromRoute("/campaigns/[campaignId]")).toBe("Campaigns CampaignId");
  });

  it("collapses index modules into stable module path keys", () => {
    expect(modulePathKey("src/backend/server/campaigns/index.ts")).toBe("src/backend/server/campaigns");
    expect(modulePathKey("src/backend/server/campaigns.ts")).toBe("src/backend/server/campaigns");
  });

  it("dedupes overlay targets by kind and value", () => {
    expect(
      dedupeTargets([
        { kind: "testId", value: "save-button", confidence: "high" },
        { kind: "testId", value: "save-button", confidence: "medium" },
        { kind: "text", value: "Save", confidence: "medium" },
      ])
    ).toEqual([
      { kind: "testId", value: "save-button", confidence: "high" },
      { kind: "text", value: "Save", confidence: "medium" },
    ]);
  });

  it("normalizes request paths and selection types", () => {
    expect(toApiRequestPath("/campaigns")).toBe("/api/campaigns");
    expect(toSelectionType("integration", "http")).toBe("int");
    expect(toSelectionType("ui", "playwright")).toBe("pw");
  });

  it("matches dynamic API route patterns against concrete and template-like request paths", () => {
    expect(routePatternMatchesCandidate("/api/projects/[projectId]/overview", "/api/projects/123/overview")).toBe(true);
    expect(
      routePatternMatchesCandidate(
        "/api/projects/[projectId]/events",
        `/api/projects/${DYNAMIC_SEGMENT_TOKEN}/events`
      )
    ).toBe(true);
    expect(routePatternMatchesCandidate("/api/projects/[projectId]/events", "/api/projects/123/stats")).toBe(false);
  });

  it("prefers the most specific matching API route entry", () => {
    const routeEntry = findMatchingApiRouteEntry("GET", "/api/projects/123/events", [
      { method: "GET", requestPath: "/api/projects/[projectId]" },
      { method: "GET", requestPath: "/api/projects/[projectId]/events" },
    ]);

    expect(routeEntry).toEqual({
      method: "GET",
      requestPath: "/api/projects/[projectId]/events",
    });
  });

  it("matches dynamic page routes against discovered route patterns", () => {
    expect(
      findMatchingRouteValue(`/projects/${DYNAMIC_SEGMENT_TOKEN}`, ["/projects/[projectId]", "/projects"])
    ).toBe("/projects/[projectId]");
  });
});
