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

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

  it("routes task action execution through the real notification router path", async () => {
    const db = {
      user: {
        findUnique: vi.fn().mockResolvedValue({ id: "user_1" }),
      },
      notification: {
        findFirst: vi.fn().mockResolvedValue({
          id: "task_1",
          userId: "user_1",
          assigneeId: null,
          taskAction: "approve_vacation:vac_1",
          taskStatus: "OPEN",
        }),
        update: vi.fn().mockResolvedValue({
          id: "task_1",
          taskStatus: "DONE",
          completedBy: "user_1",
        }),
      },
      vacation: {
        findUnique: vi.fn().mockResolvedValue({
          id: "vac_1",
          status: "PENDING",
        }),
        update: vi.fn().mockResolvedValue({
          id: "vac_1",
          status: "APPROVED",
        }),
      },
    };
    const ctx = createToolContext(db, { userRole: SystemRole.ADMIN });

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

    expect(db.notification.findFirst).toHaveBeenCalledWith({
      where: {
        id: "task_1",
        OR: [{ userId: "user_1" }, { assigneeId: "user_1" }],
        category: { in: ["TASK", "APPROVAL"] },
      },
      select: {
        id: true,
        userId: true,
        assigneeId: true,
        taskAction: true,
        taskStatus: true,
      },
    });
    expect(db.vacation.update).toHaveBeenCalledWith({
      where: { id: "vac_1" },
      data: { status: "APPROVED" },
    });
    expect(db.notification.update).toHaveBeenCalledWith({
      where: { id: "task_1" },
      data: expect.objectContaining({
        taskStatus: "DONE",
        completedBy: "user_1",
        completedAt: expect.any(Date),
      }),
    });
    expect(JSON.parse(result.content)).toEqual(
      expect.objectContaining({
        success: true,
        message: "Vacation approved",
        task: expect.objectContaining({
          id: "task_1",
          taskStatus: "DONE",
        }),
      }),
    );
  });
});
