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 create and update tools - success", () => {
  beforeEach(() => {
    vi.clearAllMocks();
    vi.mocked(countPlanningEntries).mockResolvedValue({ countsByRoleId: new Map() });
  });

  it("routes create and update client mutations through their backing router", async () => {
    const db = {
      client: {
        findUnique: vi.fn().mockImplementation(async (args?: { where?: { id?: string; code?: string } }) => {
          if (args?.where?.id === "client_1") {
            return {
              id: "client_1",
              name: "Acme",
              code: "ACME",
              parentId: null,
              isActive: true,
              sortOrder: 0,
              tags: [],
            };
          }
          if (args?.where?.code === "ACME-NEW") {
            return null;
          }
          return null;
        }),
        create: vi.fn().mockResolvedValue({
          id: "client_1",
          name: "Acme",
          code: "ACME",
          parentId: null,
          isActive: true,
          sortOrder: 2,
          tags: ["key"],
        }),
        update: vi.fn().mockResolvedValue({
          id: "client_1",
          name: "Acme Updated",
          code: "ACME-NEW",
          parentId: null,
          isActive: false,
          sortOrder: 3,
          tags: ["vip"],
        }),
      },
      auditLog: {
        create: vi.fn().mockResolvedValue({ id: "audit_1" }),
      },
    };
    const ctx = createToolContext(db, { userRole: SystemRole.ADMIN });

    const createClientResult = await executeTool(
      "create_client",
      JSON.stringify({ name: "Acme", code: "ACME", sortOrder: 2, tags: ["key"] }),
      ctx,
    );
    const updateClientResult = await executeTool(
      "update_client",
      JSON.stringify({
        id: "client_1",
        name: "Acme Updated",
        code: "ACME-NEW",
        sortOrder: 3,
        isActive: false,
        tags: ["vip"],
      }),
      ctx,
    );

    expect(JSON.parse(createClientResult.content)).toEqual(
      expect.objectContaining({
        success: true,
        clientId: "client_1",
        message: "Created client: Acme",
      }),
    );
    expect(JSON.parse(updateClientResult.content)).toEqual(
      expect.objectContaining({
        success: true,
        clientId: "client_1",
        message: "Updated client: Acme Updated",
      }),
    );

    expect(db.client.create).toHaveBeenCalled();
    expect(db.client.update).toHaveBeenCalled();
    expect(db.auditLog.create).toHaveBeenCalled();
  });

  it("returns the expected assistant payloads for create and update client mutations", 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",
              code: "AC",
              sortOrder: 0,
              isActive: true,
              parentId: null,
              tags: [],
              _count: { projects: 0, children: 0 },
            };
          }

          return null;
        }),
        create: vi.fn().mockResolvedValue({
          id: "client_1",
          name: "Acme",
          code: "AC",
          parentId: null,
          sortOrder: 2,
          tags: ["auto"],
        }),
        update: vi.fn().mockResolvedValue({
          id: "client_1",
          name: "Acme Mobility",
          code: "ACM",
          parentId: null,
          sortOrder: 3,
          tags: ["auto", "priority"],
          isActive: true,
        }),
      },
      auditLog: {
        create: vi.fn().mockResolvedValue({ id: "audit_1" }),
      },
    };
    const ctx = createToolContext(db, { userRole: SystemRole.ADMIN });

    const createClientResult = await executeTool(
      "create_client",
      JSON.stringify({ name: "Acme", code: "AC", sortOrder: 2, tags: ["auto"] }),
      ctx,
    );
    const updateClientResult = await executeTool(
      "update_client",
      JSON.stringify({
        id: "client_1",
        name: "Acme Mobility",
        code: "ACM",
        sortOrder: 3,
        tags: ["auto", "priority"],
      }),
      ctx,
    );

    expect(JSON.parse(createClientResult.content)).toEqual(
      expect.objectContaining({
        success: true,
        message: "Created client: Acme",
      }),
    );
    expect(JSON.parse(updateClientResult.content)).toEqual(
      expect.objectContaining({
        success: true,
        message: "Updated client: Acme Mobility",
      }),
    );
  });
});
