import { beforeEach, describe, expect, it, vi } from "vitest";
import { SystemRole } from "@capakraken/shared";
import {
  createToolContext,
  executeTool,
  withUserLookup,
} from "./assistant-tools-task-workflow-test-helpers.js";

describe("assistant task workflow tools - status", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("maps taskId to the router id when updating task status and returns invalidate metadata", async () => {
    const db = withUserLookup({
      notification: {
        findFirst: vi.fn().mockResolvedValue({
          id: "task_1",
          userId: "user_1",
          assigneeId: "user_2",
        }),
        update: vi.fn().mockResolvedValue({
          id: "task_1",
          taskStatus: "DONE",
        }),
      },
    });
    const ctx = createToolContext(db, SystemRole.USER);

    const result = await executeTool(
      "update_task_status",
      JSON.stringify({ taskId: "task_1", status: "DONE" }),
      ctx,
    );

    expect(db.notification.findFirst).toHaveBeenCalledWith({
      where: {
        id: "task_1",
        OR: [{ userId: "user_1" }, { assigneeId: "user_1" }],
        category: { in: ["TASK", "APPROVAL"] },
      },
    });
    expect(db.notification.update).toHaveBeenCalledWith({
      where: { id: "task_1" },
      data: {
        taskStatus: "DONE",
        completedAt: expect.any(Date),
        completedBy: "user_1",
      },
    });
    expect(result.action).toEqual({ type: "invalidate", scope: ["notification"] });
    expect(result.data).toEqual(
      expect.objectContaining({
        success: true,
        message: "Task status updated to DONE.",
        task: expect.objectContaining({
          id: "task_1",
          taskStatus: "DONE",
        }),
      }),
    );
  });

  it("returns a stable assistant error when updating a missing task", async () => {
    const ctx = createToolContext(
      withUserLookup({
        notification: {
          findFirst: vi.fn().mockResolvedValue(null),
        },
      }),
      SystemRole.ADMIN,
    );

    const result = await executeTool(
      "update_task_status",
      JSON.stringify({ taskId: "task_missing", status: "DONE" }),
      ctx,
    );

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