import { beforeEach, describe, expect, it, vi } from "vitest";
import { PermissionKey, SystemRole } from "@capakraken/shared";
import {
  createToolContext,
  executeTool,
} from "./assistant-tools-resource-admin-create-test-helpers.js";

describe("assistant resource admin create tools - success", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("routes resource creation through the real resource router path and writes an audit log", async () => {
    const auditCreate = vi.fn().mockResolvedValue({ id: "audit_1" });
    const resourceFindFirst = vi.fn().mockResolvedValue(null);
    const resourceCreate = vi.fn().mockResolvedValue({
      id: "res_1",
      eid: "EMP-001",
      displayName: "Carol Danvers",
      email: "carol@example.com",
      resourceRoles: [],
    });
    const ctx = createToolContext(
      {
        resource: {
          findFirst: resourceFindFirst,
          create: resourceCreate,
        },
        role: {
          findUnique: vi.fn().mockResolvedValue({
            id: "role_1",
            name: "Designer",
            _count: { resourceRoles: 0 },
          }),
          findFirst: vi.fn().mockResolvedValue(null),
        },
        country: {
          findUnique: vi.fn().mockResolvedValue({
            id: "country_de",
            code: "DE",
            name: "Germany",
            metroCities: [],
            _count: { resources: 0 },
          }),
          findFirst: vi.fn().mockResolvedValue(null),
        },
        orgUnit: {
          findUnique: vi.fn().mockResolvedValue({
            id: "ou_1",
            name: "Delivery",
            shortName: "DEL",
            _count: { resources: 0 },
          }),
          findFirst: vi.fn().mockResolvedValue(null),
        },
        assignment: {
          findMany: vi.fn().mockResolvedValue([]),
        },
        demandRequirement: {
          findMany: vi.fn().mockResolvedValue([]),
        },
        auditLog: {
          create: auditCreate,
        },
      },
      {
        userRole: SystemRole.ADMIN,
        permissions: [PermissionKey.MANAGE_RESOURCES],
      },
    );

    const result = await executeTool(
      "create_resource",
      JSON.stringify({
        eid: "EMP-001",
        displayName: "Carol Danvers",
        email: "carol@example.com",
        lcrCents: 8000,
        roleName: "Designer",
        countryCode: "DE",
        orgUnitName: "Delivery",
      }),
      ctx,
    );

    expect(JSON.parse(result.content)).toEqual(
      expect.objectContaining({
        success: true,
        message: "Created resource: Carol Danvers (EMP-001)",
      }),
    );
    expect(resourceFindFirst).toHaveBeenCalled();
    expect(resourceCreate).toHaveBeenCalledWith(
      expect.objectContaining({
        data: expect.objectContaining({
          roleId: "role_1",
          countryId: "country_de",
          orgUnitId: "ou_1",
        }),
      }),
    );
    expect(auditCreate).toHaveBeenCalledTimes(1);
  });
});
