import type { FastifyRequest } from 'fastify';
import { BadRequestError } from './errors.js';
import { PRODUCT_ID } from './product-config.js';

export interface JwtPayload {
  sub: string;
  email?: string;
  role?: string;
  productId?: string;
  type?: string;
}

declare module 'fastify' {
  interface FastifyRequest {
    jwtPayload?: JwtPayload;
  }
}

export function getRequestProductId(req: FastifyRequest): string {
  const jwtPid = req.jwtPayload?.productId;
  if (jwtPid && jwtPid !== PRODUCT_ID) {
    throw new BadRequestError(`Invalid productId: expected ${PRODUCT_ID}, got ${jwtPid}`);
  }

  const header = req.headers['x-product-id'];
  if (typeof header === 'string' && header.length > 0 && header !== PRODUCT_ID) {
    throw new BadRequestError(`Invalid productId: expected ${PRODUCT_ID}, got ${header}`);
  }

  return PRODUCT_ID;
}
