import type { Request } from 'express';
import { normalizeLocale } from '@thebet365/shared';

export function resolveRequestLocale(req: Request): string {
  const xLocale = req.headers['x-locale'];
  if (typeof xLocale === 'string' && xLocale.trim()) {
    return normalizeLocale(xLocale);
  }

  const queryLocale = req.query?.locale;
  if (typeof queryLocale === 'string' && queryLocale.trim()) {
    return normalizeLocale(queryLocale);
  }

  const accept = req.headers['accept-language'];
  if (typeof accept === 'string' && accept.trim()) {
    const first = accept.split(',')[0]?.trim();
    if (first) return normalizeLocale(first);
  }

  return normalizeLocale(undefined);
}
