import { 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, type ToolContext } from "../router/assistant-tools.js";

function createToolContext(
  db: Record<string, unknown>,
  userRole: SystemRole = SystemRole.CONTROLLER,
): ToolContext {
  return {
    db: db as ToolContext["db"],
    userId: "user_1",
    userRole,
    permissions: new Set(),
    session: {
      user: { email: "assistant@example.com", name: "Assistant User", image: null },
      expires: "2026-03-29T00:00:00.000Z",
    },
    dbUser: {
      id: "user_1",
      systemRole: userRole,
      permissionOverrides: null,
    },
    roleDefaults: null,
  };
}

describe("assistant audit tools", () => {
  it("lists audit entries 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: "ui",
            summary: "Updated project dates",
            createdAt: new Date("2026-03-28T10:00:00.000Z"),
            user: {
              id: "user_1",
              name: "Larissa",
              email: "larissa@example.com",
            },
          },
        ]),
      },
    });

    const result = await executeTool(
      "list_audit_log_entries",
      JSON.stringify({
        entityType: "Project",
        search: "Gelddruckmaschine",
        limit: 10,
      }),
      ctx,
    );

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

  it("enforces controller access for audit tools via the backing router", async () => {
    const ctx = createToolContext(
      {
        auditLog: {
          findMany: vi.fn(),
        },
      },
      SystemRole.USER,
    );

    const result = await executeTool(
      "query_change_history",
      JSON.stringify({ entityType: "Project" }),
      ctx,
    );

    expect(JSON.parse(result.content)).toEqual(
      expect.objectContaining({
        error: expect.stringContaining("Controller access required"),
      }),
    );
  });
});
