import { createMiddleware } from "@tanstack/react-start";

/**
 * Optional session middleware — resolves `context.userId` when signed in,
 * otherwise `null`. Forwards live-preview bearer tokens. Never throws.
 */
export const optionalAuthMiddleware = createMiddleware({ type: "function" })
  .client(async ({ next }) => {
    const { getBearerToken } = await import("./client");
    return next({ sendContext: { bearerToken: getBearerToken() ?? undefined } });
  })
  .server(async ({ next, context }) => {
    const { getSessionUser } = await import("./verify.server");
    const user = await getSessionUser(context.bearerToken).catch(() => null);
    return next({ context: { userId: user?.id ?? null as string | null } });
  });
