import { createTRPCContext, loadRoleDefaults } from "@capakraken/api";
import { appRouter } from "@capakraken/api/router";
import { createCallerFactory } from "@capakraken/api/trpc";
import { prisma } from "@capakraken/db";
import { auth } from "./auth.js";

/**
 * Server-side tRPC caller for RSC.
 * Usage: const trpc = await createCaller(); const result = await trpc.resource.directory({});
 */
export async function createCaller() {
  const session = await auth();

  const dbUser = session?.user?.email
    ? await prisma.user.findUnique({
        where: { email: session.user.email },
        select: { id: true, systemRole: true, permissionOverrides: true },
      })
    : null;

  const roleDefaults = await loadRoleDefaults();
  const ctx = createTRPCContext({ session, dbUser, roleDefaults });
  const callerFactory = createCallerFactory(appRouter);
  return callerFactory(ctx);
}
