import { PermissionKey, SystemRole } from "@nexus/shared";

import type { ToolContext } from "../router/assistant-tools.js";

import { vi } from "vitest";

const defaultDbDefaults = {
  blueprint: {
    findUnique: vi.fn().mockResolvedValue(null),
    findMany: vi.fn().mockResolvedValue([]),
  },
};

export function createToolContext(
  db: Record<string, unknown>,
  options?: {
    permissions?: PermissionKey[];
    userRole?: SystemRole;
  },
): ToolContext {
  const userRole = options?.userRole ?? SystemRole.ADMIN;
  const mergedDb: Record<string, unknown> = {
    ...defaultDbDefaults,
    ...db,
    blueprint: {
      ...defaultDbDefaults.blueprint,
      ...(db.blueprint as Record<string, unknown> | undefined),
    },
  };
  if (!mergedDb["$transaction"]) {
    mergedDb["$transaction"] = vi.fn(async (fn: (tx: unknown) => unknown) => fn(mergedDb));
  }
  return {
    db: mergedDb as ToolContext["db"],
    userId: "user_1",
    userRole,
    permissions: new Set(options?.permissions ?? []),
    session: {
      user: { email: "assistant@example.com", name: "Assistant User", image: null },
      expires: "2026-03-29T00:00:00.000Z",
    },
    dbUser: {
      id: "user_1",
      systemRole: userRole,
      permissionOverrides: null,
    },
    roleDefaults: null,
  };
}
