export const MARKETPLACE_ORIGIN = 'https://app.rwatokenizationplatform.com';

/** Public origin is explicit in production; never trust forwarded headers here. */
export function applicationOrigin(request: Request): string {
  const production = process.env.NODE_ENV === 'production';
  const configured = process.env.APP_URL?.trim();
  if (!configured && !production) return new URL(request.url).origin;
  const url = new URL(configured || MARKETPLACE_ORIGIN);
  const local = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
  if (url.username || url.password || url.search || url.hash || url.pathname !== '/' ||
    (url.protocol !== 'https:' && !(url.protocol === 'http:' && !production && local))) {
    throw new Error('APP_URL must be an exact HTTPS origin');
  }
  return url.origin;
}
