import { beforeEach, describe, expect, it, vi } from "vitest";
import { TRPCError } from "@trpc/server";
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 reminder creation tools - persistence errors", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("returns a stable assistant error when reminder creation loses its authenticated user", async () => {
    const ctx = createToolContext(
      {
        user: {
          findUnique: vi.fn().mockResolvedValue({ id: "user_1" }),
        },
        notification: {
          create: vi.fn().mockRejectedValue({
            code: "P2003",
            message: "Foreign key constraint failed",
            meta: { field_name: "Notification_userId_fkey" },
          }),
        },
      },
      SystemRole.ADMIN,
    );

    const result = await executeTool(
      "create_reminder",
      JSON.stringify({
        title: "Submit report",
        remindAt: "2026-04-01T09:00:00.000Z",
      }),
      ctx,
    );

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

  it("returns a stable assistant error when reminder creation is rejected by the backing router", async () => {
    const ctx = createToolContext(
      {
        user: {
          findUnique: vi.fn().mockResolvedValue({ id: "user_1" }),
        },
        notification: {
          create: vi.fn(),
        },
      },
      SystemRole.ADMIN,
    );

    ctx.db.notification.create.mockRejectedValue(
      new TRPCError({
        code: "BAD_REQUEST",
        message: "Reminder payload is invalid",
      }),
    );

    const result = await executeTool(
      "create_reminder",
      JSON.stringify({
        title: "Submit report",
        remindAt: "2026-04-01T09:00:00.000Z",
      }),
      ctx,
    );

    expect(JSON.parse(result.content)).toEqual({
      error: "Reminder input is invalid.",
    });
  });
});
