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 audit entity and summary tools", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("returns an entity-scoped audit timeline through the real audit router path", async () => {
    const ctx = createToolContext(
      {
        auditLog: {
          findMany: vi.fn().mockResolvedValue([
            {
              id: "audit_entity_1",
              entityType: "resource",
              entityId: "resource_1",
              entityName: "Peter Parker",
              action: "updated",
              userId: "user_2",
              source: "assistant",
              summary: "Updated local holiday scope",
              changes: { federalState: ["HH", "BY"] },
              createdAt: new Date("2026-03-30T08:00:00.000Z"),
              user: {
                id: "user_2",
                name: "Audit User",
                email: "audit@example.com",
              },
            },
          ]),
        },
      },
      { userRole: SystemRole.CONTROLLER },
    );

    const result = await executeTool(
      "get_entity_timeline",
      JSON.stringify({
        entityType: "resource",
        entityId: "resource_1",
        limit: 10,
      }),
      ctx,
    );

    expect(JSON.parse(result.content)).toEqual({
      entityType: "resource",
      entityId: "resource_1",
      entityName: "Peter Parker",
      itemCount: 1,
      items: [
        {
          id: "audit_entity_1",
          entityType: "resource",
          entityId: "resource_1",
          entityName: "Peter Parker",
          action: "updated",
          userId: "user_2",
          source: "assistant",
          summary: "Updated local holiday scope",
          createdAt: "2026-03-30T08:00:00.000Z",
          changes: { federalState: ["HH", "BY"] },
          user: {
            id: "user_2",
            name: "Audit User",
            email: "audit@example.com",
          },
        },
      ],
    });
  });

  it("returns audit activity summary buckets through the real audit router path", async () => {
    const ctx = createToolContext(
      {
        auditLog: {
          groupBy: vi
            .fn()
            .mockResolvedValueOnce([
              { entityType: "Project", _count: { id: 3 } },
              { entityType: "Resource", _count: { id: 2 } },
            ])
            .mockResolvedValueOnce([
              { action: "CREATE", _count: { id: 2 } },
              { action: "UPDATE", _count: { id: 3 } },
            ])
            .mockResolvedValueOnce([
              { userId: "user_1", _count: { id: 4 } },
              { userId: "user_2", _count: { id: 1 } },
            ]),
          count: vi.fn().mockResolvedValue(5),
        },
        user: {
          findMany: vi.fn().mockResolvedValue([
            { id: "user_1", name: "Larissa", email: "larissa@example.com" },
            { id: "user_2", name: null, email: "audit@example.com" },
          ]),
        },
      },
      { userRole: SystemRole.CONTROLLER },
    );

    const result = await executeTool(
      "get_audit_activity_summary",
      JSON.stringify({
        startDate: "2026-03-01",
        endDate: "2026-03-31",
      }),
      ctx,
    );

    expect(JSON.parse(result.content)).toEqual({
      byEntityType: {
        Project: 3,
        Resource: 2,
      },
      byAction: {
        CREATE: 2,
        UPDATE: 3,
      },
      byUser: [
        { name: "Larissa", count: 4 },
        { name: "audit@example.com", count: 1 },
      ],
      total: 5,
    });
  });
});
