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,
    countPlanningEntries: vi.fn().mockResolvedValue({ countsByRoleId: new Map() }),
    getDashboardBudgetForecast: vi.fn().mockResolvedValue([]),
    getDashboardPeakTimes: vi.fn().mockResolvedValue([]),
    listAssignmentBookings: vi.fn().mockResolvedValue([]),
  };
});

import { countPlanningEntries } from "@capakraken/application";
import { executeTool } from "../router/assistant-tools.js";
import { createToolContext } from "./assistant-tools-master-data-mutation-test-helpers.js";

describe("assistant client delete tool - success", () => {
  beforeEach(() => {
    vi.clearAllMocks();
    vi.mocked(countPlanningEntries).mockResolvedValue({ countsByRoleId: new Map() });
  });

  it("returns the expected assistant payload for deleting a client", async () => {
    const db = {
      client: {
        findUnique: vi.fn(async ({ where }: { where: { id?: string; code?: string } }) => {
          if (where.id === "client_1") {
            return {
              id: "client_1",
              name: "Acme Mobility",
              code: "ACM",
              parentId: null,
              sortOrder: 3,
              tags: ["auto", "priority"],
              isActive: true,
              _count: { projects: 0, children: 0 },
            };
          }
          return null;
        }),
        delete: vi.fn().mockResolvedValue({
          id: "client_1",
          name: "Acme Mobility",
          code: "ACM",
          parentId: null,
          sortOrder: 3,
          tags: ["auto", "priority"],
          isActive: true,
          _count: { projects: 0, children: 0 },
        }),
      },
      auditLog: {
        create: vi.fn().mockResolvedValue({ id: "audit_1" }),
      },
    };
    const ctx = createToolContext(db, { userRole: SystemRole.ADMIN });

    const deleteClientResult = await executeTool(
      "delete_client",
      JSON.stringify({ id: "client_1" }),
      ctx,
    );

    expect(JSON.parse(deleteClientResult.content)).toEqual(
      expect.objectContaining({
        success: true,
        message: "Deleted client: Acme Mobility",
      }),
    );
    expect(db.client.delete).toHaveBeenCalledWith({ where: { id: "client_1" } });
    expect(db.auditLog.create).toHaveBeenCalled();
  });
});
