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,
    getDashboardBudgetForecast: vi.fn().mockResolvedValue([]),
    getDashboardPeakTimes: vi.fn().mockResolvedValue([]),
    listAssignmentBookings: vi.fn().mockResolvedValue([]),
  };
});

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

describe("assistant user self-service column preferences tools", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("reads column preferences through the real user router path", async () => {
    const db = {
      user: {
        findUnique: vi.fn().mockResolvedValue({
          columnPreferences: {
            resources: {
              visible: ["name", "role"],
              sort: { field: "name", dir: "asc" },
            },
          },
        }),
      },
    };
    const ctx = createToolContext(db, SystemRole.ADMIN);

    const result = await executeTool("get_column_preferences", "{}", ctx);

    expect(db.user.findUnique).toHaveBeenCalledWith({
      where: { id: "user_1" },
      select: { columnPreferences: true },
    });
    expect(JSON.parse(result.content)).toEqual({
      resources: {
        visible: ["name", "role"],
        sort: { field: "name", dir: "asc" },
      },
    });
  });

  it("updates column preferences through the real user router path", async () => {
    const db = {
      user: {
        findUnique: vi.fn().mockResolvedValue({
          columnPreferences: {
            resources: {
              visible: ["name", "role"],
              sort: { field: "name", dir: "asc" },
              rowOrder: ["name", "role", "email"],
            },
          },
        }),
        update: vi.fn().mockResolvedValue({ id: "user_1" }),
      },
    };
    const ctx = createToolContext(db, SystemRole.ADMIN);

    const result = await executeTool(
      "set_column_preferences",
      JSON.stringify({
        view: "resources",
        visible: ["name", "email"],
      }),
      ctx,
    );

    expect(db.user.update).toHaveBeenCalledWith({
      where: { id: "user_1" },
      data: {
        columnPreferences: {
          resources: {
            visible: ["name", "email"],
            sort: { field: "name", dir: "asc" },
            rowOrder: ["name", "role", "email"],
          },
        },
      },
    });
    expect(JSON.parse(result.content)).toEqual({
      success: true,
      ok: true,
      message: "Updated column preferences for resources.",
    });
    expect(result.action).toEqual({
      type: "invalidate",
      scope: ["user"],
    });
  });
});
