import path from "path";
import { describe, expect, it } from "vitest";
import {
  inferApiRoutesFromTestFile,
  inferOwnerDirectoryFromTestFile,
  inferPageRouteFromTestFile,
  normalizeRouteSegments,
  pathMatchesOwner,
  routeFromApiFile,
  routeFromAppFile,
} from "./routing.mjs";

describe("coverage routing helpers", () => {
  it("normalizes route segments by stripping route groups and slots", () => {
    expect(normalizeRouteSegments(["(marketing)", "@modal", "campaigns", "[campaignId]", "page"])).toBe(
      "/campaigns/[campaignId]"
    );
  });

  it("infers page ownership routes from colocated __testkit__ files", () => {
    const serviceRoot = "/repo";
    const nextAppRoot = path.join(serviceRoot, "src", "app");

    expect(
      inferPageRouteFromTestFile("src/app/campaigns/[campaignId]/__testkit__/details.pw.testkit.ts", nextAppRoot, serviceRoot)
    ).toBe("/campaigns/[campaignId]");
  });

  it("infers API routes from colocated __testkit__ files", () => {
    const serviceRoot = "/repo";
    const nextAppRoot = path.join(serviceRoot, "src", "app");

    expect(
      inferApiRoutesFromTestFile("src/app/api/campaigns/__testkit__/create.int.testkit.ts", nextAppRoot, serviceRoot)
    ).toEqual(["/campaigns"]);
  });

  it("derives page and API routes from Next app file paths", () => {
    const nextAppRoot = "/repo/src/app";

    expect(routeFromAppFile(nextAppRoot, "/repo/src/app/settings/page.tsx")).toBe("/settings");
    expect(routeFromApiFile(nextAppRoot, "/repo/src/app/api/campaigns/route.ts")).toBe("/campaigns");
  });

  it("matches nested ownership directories for DAL evidence", () => {
    expect(inferOwnerDirectoryFromTestFile("src/backend/data/campaigns/__testkit__/save.dal.testkit.ts")).toBe(
      "src/backend/data/campaigns"
    );
    expect(pathMatchesOwner("src/backend/data/campaigns/index.ts", "src/backend/data/campaigns")).toBe(true);
    expect(pathMatchesOwner("src/backend/data/other/index.ts", "src/backend/data/campaigns")).toBe(false);
  });
});
