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,
    approveEstimateVersion: vi.fn(),
    cloneEstimate: vi.fn(),
    commitDispoImportBatch: vi.fn(),
    countPlanningEntries: vi.fn().mockResolvedValue({ countsByRoleId: new Map() }),
    createEstimateExport: vi.fn(),
    createEstimatePlanningHandoff: vi.fn(),
    createEstimateRevision: vi.fn(),
    assessDispoImportReadiness: vi.fn(),
    loadResourceDailyAvailabilityContexts: vi.fn().mockResolvedValue(new Map()),
    getDashboardDemand: vi.fn().mockResolvedValue([]),
    getDashboardBudgetForecast: vi.fn().mockResolvedValue([]),
    getDashboardOverview: vi.fn(),
    getDashboardSkillGapSummary: vi.fn().mockResolvedValue({
      roleGaps: [],
      totalOpenPositions: 0,
      skillSupplyTop10: [],
      resourcesByRole: [],
    }),
    getDashboardProjectHealth: vi.fn().mockResolvedValue([]),
    getDashboardPeakTimes: vi.fn().mockResolvedValue([]),
    getDashboardTopValueResources: vi.fn().mockResolvedValue([]),
    getEstimateById: vi.fn(),
    listAssignmentBookings: vi.fn().mockResolvedValue([]),
    stageDispoImportBatch: vi.fn(),
    submitEstimateVersion: vi.fn(),
    updateEstimateDraft: vi.fn(),
  };
});

import { executeTool } from "../router/assistant-tools.js";
import { createToolContext } from "./assistant-tools-notification-test-helpers.js";

describe("assistant task creation tools errors", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("returns a stable assistant error when task dueDate is invalid", async () => {
    const ctx = createToolContext({}, SystemRole.MANAGER);

    const result = await executeTool(
      "create_task_for_user",
      JSON.stringify({
        userId: "user_2",
        title: "Follow up",
        dueDate: "not-a-datetime",
      }),
      ctx,
    );

    expect(JSON.parse(result.content)).toEqual({
      error: "Invalid dueDate: not-a-datetime",
    });
  });

  it("returns a stable assistant error when task recipient user is missing", async () => {
    const ctx = createToolContext(
      {
        notification: {
          create: vi.fn().mockRejectedValue({
            code: "P2003",
            message: "Foreign key constraint failed",
            meta: { field_name: "Notification_userId_fkey" },
          }),
        },
      },
      SystemRole.MANAGER,
    );

    const result = await executeTool(
      "create_task_for_user",
      JSON.stringify({
        userId: "user_missing",
        title: "Follow up",
      }),
      ctx,
    );

    expect(JSON.parse(result.content)).toEqual({
      error: "Task recipient user not found with the given criteria.",
    });
  });

  it("returns a stable assistant error when task sender user is missing", async () => {
    const ctx = createToolContext(
      {
        notification: {
          create: vi.fn().mockRejectedValue({
            code: "P2003",
            message: "Foreign key constraint failed",
            meta: { field_name: "Notification_senderId_fkey" },
          }),
        },
      },
      SystemRole.MANAGER,
    );

    const result = await executeTool(
      "create_task_for_user",
      JSON.stringify({
        userId: "user_2",
        title: "Follow up",
      }),
      ctx,
    );

    expect(JSON.parse(result.content)).toEqual({
      error: "Sender user not found with the given criteria.",
    });
  });
});
