import { beforeEach, describe, expect, it, vi } from "vitest";
import { SystemRole } from "@capakraken/shared";

vi.mock("@capakraken/application", async (importOriginal) => {
  const actual = await importOriginal<typeof import("@capakraken/application")>();
  return {
    ...actual,
    getDashboardBudgetForecast: vi.fn().mockResolvedValue([]),
    getDashboardPeakTimes: vi.fn().mockResolvedValue([]),
    listAssignmentBookings: vi.fn().mockResolvedValue([]),
  };
});

import { executeTool } from "../router/assistant-tools.js";
import { createToolContext } from "./assistant-tools-audit-task-test-helpers.js";

describe("assistant query change history tool", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("queries recent change history through the real audit router path", async () => {
    const ctx = createToolContext(
      {
        auditLog: {
          findMany: vi.fn().mockResolvedValue([
            {
              id: "audit_1",
              entityType: "Project",
              entityId: "project_1",
              entityName: "Gelddruckmaschine",
              action: "UPDATE",
              userId: "user_1",
              source: "assistant",
              summary: "Adjusted project margin",
              createdAt: new Date("2026-03-28T10:00:00.000Z"),
              user: {
                id: "user_1",
                name: "Larissa",
                email: "larissa@example.com",
              },
            },
          ]),
        },
      },
      { userRole: SystemRole.CONTROLLER },
    );

    const result = await executeTool(
      "query_change_history",
      JSON.stringify({
        entityType: "Project",
        search: "Gelddruckmaschine",
        action: "UPDATE",
        daysBack: 14,
        limit: 5,
      }),
      ctx,
    );

    expect(JSON.parse(result.content)).toEqual({
      filters: {
        entityType: "Project",
        userId: null,
        action: "UPDATE",
        search: "Gelddruckmaschine",
        daysBack: 14,
      },
      itemCount: 1,
      nextCursor: null,
      items: [
        {
          id: "audit_1",
          entityType: "Project",
          entityId: "project_1",
          entityName: "Gelddruckmaschine",
          action: "UPDATE",
          userId: "user_1",
          source: "assistant",
          summary: "Adjusted project margin",
          createdAt: "2026-03-28T10:00:00.000Z",
          user: {
            id: "user_1",
            name: "Larissa",
            email: "larissa@example.com",
          },
        },
      ],
    });
  });
});
