import { config } from '../config';

/** Sinsay production key (referer: https://www.sinsay.com/* only). */
export const SINSAY_GOOGLE_MAPS_KEY = 'AIzaSyBd_a_c8FDJE4HVnxbgh4FbwSUrnztHG9c';

const SINSAY_MAPS_REFERER = 'https://www.sinsay.com/';
const SINSAY_MAPS_ORIGIN = 'https://www.sinsay.com';

export function googleMapsApiKey(): string {
  return config.googleMaps.effectiveKey;
}

export function googleMapsUsesMirrorKey(): boolean {
  return config.googleMaps.useMirrorKey;
}

/** Referer/origin sent to Google from the server-side maps proxy. */
export function googleMapsProxyAuth(): { referer: string; origin: string } {
  if (config.googleMaps.useMirrorKey) {
    const origin = config.origin.replace(/\/$/, '');
    return { referer: `${origin}/`, origin };
  }
  return { referer: SINSAY_MAPS_REFERER, origin: SINSAY_MAPS_ORIGIN };
}

/** Swap Sinsay key → mirror key in HTML/JS so the browser uses a key allowed for this host. */
export function rewriteGoogleMapsApiKeys(text: string): string {
  const effective = googleMapsApiKey();
  if (effective === SINSAY_GOOGLE_MAPS_KEY) return text;
  return text.replaceAll(SINSAY_GOOGLE_MAPS_KEY, effective);
}

export function rewriteGoogleMapsKeyInQuery(query: string): string {
  if (!query) return query;
  const effective = encodeURIComponent(googleMapsApiKey());
  return query.replace(
    /([?&]key=)(AIzaSy[A-Za-z0-9_-]+)/gi,
    `$1${effective}`,
  );
}
