import { beforeEach, describe, expect, it, vi } from "vitest";

import {
  batchQuickAssignPermissions,
  batchQuickAssignRole,
  buildBaseProject,
  buildBaseResource,
  createBatchQuickAssignInput,
  createToolContext,
  executeTool,
} from "./assistant-tools-timeline-batch-quick-assign-test-helpers.js";

describe("assistant timeline batch quick-assign error tools", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("returns a structured batch assignment resolver error for an unknown resource", async () => {
    const db = {
      project: {
        findUnique: vi.fn().mockResolvedValue({
          ...buildBaseProject(),
          startDate: new Date("2026-03-16"),
          endDate: new Date("2026-03-20"),
        }),
        findFirst: vi.fn().mockResolvedValue(null),
      },
      resource: {
        findUnique: vi.fn().mockResolvedValue(null),
        findFirst: vi.fn().mockResolvedValue(null),
        findMany: vi.fn().mockResolvedValue([]),
      },
      assignment: {
        create: vi.fn(),
      },
    };
    const ctx = createToolContext(db, batchQuickAssignPermissions, batchQuickAssignRole);

    const result = await executeTool(
      "batch_quick_assign_timeline_resources",
      JSON.stringify(
        createBatchQuickAssignInput([
          {
            resourceIdentifier: "missing_resource",
          },
        ]),
      ),
      ctx,
    );

    expect(result.action).toBeUndefined();
    expect(JSON.parse(result.content)).toEqual({
      error: "assignments[0].resourceIdentifier: Resource not found: missing_resource",
      field: "assignments[0].resourceIdentifier",
      index: 0,
    });
    expect(db.assignment.create).not.toHaveBeenCalled();
  });

  it("returns a stable validation error for batch timeline mutation date ranges", async () => {
    const ctx = createToolContext(
      {
        project: {
          findUnique: vi.fn().mockResolvedValue(buildBaseProject()),
        },
        resource: {
          findUnique: vi.fn().mockResolvedValue(buildBaseResource()),
        },
      },
      batchQuickAssignPermissions,
      batchQuickAssignRole,
    );

    const result = await executeTool(
      "batch_quick_assign_timeline_resources",
      JSON.stringify(
        createBatchQuickAssignInput([
          {
            startDate: "2026-03-20",
            endDate: "2026-03-16",
          },
        ]),
      ),
      ctx,
    );

    expect(JSON.parse(result.content)).toEqual({
      error: "End date must be after start date",
    });
  });
});
