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

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

  it("routes project search through the project router path", async () => {
    const db = {
      project: {
        findMany: vi.fn().mockResolvedValue([
          {
            id: "project_1",
            shortCode: "GDM",
            name: "Gelddruckmaschine",
            status: "ACTIVE",
            budgetCents: 500_000,
            winProbability: 100,
            startDate: new Date("2026-01-01T00:00:00.000Z"),
            endDate: new Date("2026-03-31T00:00:00.000Z"),
            client: { name: "Acme Mobility" },
            _count: { assignments: 3, estimates: 1 },
          },
        ]),
      },
    };
    const ctx = createToolContext(db, { userRole: SystemRole.CONTROLLER });

    const searchResult = await executeTool(
      "search_projects",
      JSON.stringify({ query: "Gelddruckmaschine", limit: 10 }),
      ctx,
    );

    expect(db.project.findMany).toHaveBeenCalledWith({
      where: {
        OR: [
          { name: { contains: "Gelddruckmaschine", mode: "insensitive" } },
          { shortCode: { contains: "Gelddruckmaschine", mode: "insensitive" } },
        ],
      },
      select: {
        id: true,
        shortCode: true,
        name: true,
        status: true,
        budgetCents: true,
        winProbability: true,
        startDate: true,
        endDate: true,
        client: { select: { name: true } },
        _count: { select: { assignments: true, estimates: true } },
      },
      take: 10,
      orderBy: { name: "asc" },
    });
    expect(JSON.parse(searchResult.content)).toEqual([
      {
        id: "project_1",
        code: "GDM",
        name: "Gelddruckmaschine",
        status: "ACTIVE",
        budget: "5.000,00 EUR",
        winProbability: "100%",
        start: "2026-01-01",
        end: "2026-03-31",
        client: "Acme Mobility",
        assignmentCount: 3,
        estimateCount: 1,
      },
    ]);
  });
});
