/**
 * Request-level product context helpers — delegates to @bytelyst/fastify-auth.
 */
import { createRequestContext } from '@bytelyst/fastify-auth';
import type { FastifyRequest } from 'fastify';
import { BadRequestError } from '@bytelyst/errors';
import { PRODUCT_ID } from './product-config.js';

export type { JwtPayload } from '@bytelyst/fastify-auth';

const _ctx = createRequestContext({ productId: PRODUCT_ID });

export const getRequestProductId = _ctx.getRequestProductId;

/**
 * Get authenticated user ID from JWT payload.
 * Falls back to 'demo-user' in development when no JWT is present.
 */
export function getUserId(req: FastifyRequest): string {
  if (req.jwtPayload?.sub) return req.jwtPayload.sub;
  if (process.env.NODE_ENV !== 'production') return 'demo-user';
  throw new BadRequestError('Authentication required');
}
