import { beforeEach, describe, expect, it, vi } from "vitest";
import { PermissionKey, SystemRole } from "@capakraken/shared";
import { createToolContext, executeTool } from "./assistant-tools-resource-test-helpers.js";

describe("assistant resource search tool", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("routes resource search through the resource router path", async () => {
    const db = {
      resource: {
        findMany: vi.fn().mockResolvedValue([
          {
            id: "res_1",
            eid: "EMP-001",
            displayName: "Bruce Banner",
            chapter: "Delivery",
            fte: 1,
            lcrCents: 8_500,
            chargeabilityTarget: 80,
            isActive: true,
            areaRole: { name: "Pipeline TD" },
            country: { code: "DE", name: "Germany", dailyWorkingHours: 8 },
            metroCity: { name: "Munich" },
            orgUnit: { name: "Operations", level: 5 },
          },
        ]),
      },
    };
    const ctx = createToolContext(db, {
      userRole: SystemRole.CONTROLLER,
      permissions: [PermissionKey.VIEW_ALL_RESOURCES],
    });

    const searchResult = await executeTool(
      "search_resources",
      JSON.stringify({ query: "Bruce", country: "DE", roleName: "Pipeline", limit: 5 }),
      ctx,
    );

    expect(db.resource.findMany).toHaveBeenCalledWith({
      where: {
        isActive: true,
        OR: [
          { displayName: { contains: "Bruce", mode: "insensitive" } },
          { eid: { contains: "Bruce", mode: "insensitive" } },
          { chapter: { contains: "Bruce", mode: "insensitive" } },
        ],
        country: {
          OR: [
            { code: { equals: "DE", mode: "insensitive" } },
            { name: { contains: "DE", mode: "insensitive" } },
          ],
        },
        areaRole: { name: { contains: "Pipeline", mode: "insensitive" } },
      },
      select: {
        id: true,
        eid: true,
        displayName: true,
        chapter: true,
        fte: true,
        lcrCents: true,
        chargeabilityTarget: true,
        isActive: true,
        areaRole: { select: { name: true } },
        country: { select: { code: true, name: true } },
        metroCity: { select: { name: true } },
        orgUnit: { select: { name: true } },
      },
      take: 5,
      orderBy: { displayName: "asc" },
    });
    expect(JSON.parse(searchResult.content)).toEqual([
      {
        id: "res_1",
        eid: "EMP-001",
        name: "Bruce Banner",
        chapter: "Delivery",
        role: "Pipeline TD",
        country: "Germany",
        countryCode: "DE",
        metroCity: "Munich",
        orgUnit: "Operations",
        fte: 1,
        lcr: "85,00 EUR",
        chargeabilityTarget: "80%",
        active: true,
      },
    ]);
  });
});
