/**
 * Серверні хелпери: конфіг магазину за Host, кеш у пам'яті, запити до бека.
 * Auto-imports Nitro (useRuntimeConfig, getRequestHeader...) доступні без імпорту.
 */
import { computeStoreOrigin, isDevHostname, type StoreDomainInfo } from '../../utils/store-origin';

export interface ServerStoreConfig extends StoreDomainInfo {
  publicApiToken?: string;
  siteName?: string;
  [key: string]: any;
}

const TTL = 5 * 60 * 1000;
const NEG_TTL = 30 * 1000;
const cache = new Map<string, { at: number; ttl: number; value: ServerStoreConfig | null }>();

/** Піддомен із заголовка X-Subdomain (ставить template_router/nginx платформи; Host там уже переписаний). */
export const routedSubdomain = (event: any): string =>
  String(getRequestHeader(event, 'x-subdomain') || '').split(',')[0].trim().toLowerCase();

const platformBaseDomain = (): string => String((useRuntimeConfig() as any).public?.storeBaseDomain || '').trim().toLowerCase();

export const requestHostname = (event: any): string => {
  const sub = routedSubdomain(event);
  const base = platformBaseDomain();
  if (sub && base) return `${sub}.${base}`;
  return String(getRequestHeader(event, 'x-forwarded-host') || getRequestHeader(event, 'host') || '')
    .split(',')[0].trim().split(':')[0].toLowerCase();
};

export const requestOrigin = (event: any): string => {
  const sub = routedSubdomain(event);
  const base = platformBaseDomain();
  const host = sub && base
    ? `${sub}.${base}`
    : String(getRequestHeader(event, 'x-forwarded-host') || getRequestHeader(event, 'host') || 'localhost').split(',')[0].trim();
  const proto = String(getRequestHeader(event, 'x-forwarded-proto') || (isDevHostname(host.split(':')[0]) ? 'http' : 'https')).split(',')[0].trim();
  return `${proto}://${host}`;
};

/** Базовий URL бека для серверних запитів. */
export const apiBase = (): string => {
  const c = useRuntimeConfig() as any;
  const base = String(c.apiBaseInternal || c.public?.apiBase || '');
  return /^https?:\/\//.test(base) ? base : 'http://localhost:3001/api';
};

/** Піддомен за Host — те саме правило, що й useSiteConfig.getSubdomain. */
const subdomainOf = (hostname: string): string | null => {
  const parts = hostname.split('.');
  if (parts.length === 2 && parts[1] === 'localhost') return parts[0];
  if (parts.length >= 3) return parts[0];
  return null;
};

const fetchConfig = async (path: string): Promise<ServerStoreConfig | null> => {
  try {
    return await $fetch<ServerStoreConfig>(path, { baseURL: apiBase(), timeout: 5000 });
  } catch {
    return null;
  }
};

/** Конфіг магазину за хостом запиту (кеш 5 хв; невдачі кешуємо на 30 с). */
export const getStoreConfig = async (event: any): Promise<ServerStoreConfig | null> => {
  const c = useRuntimeConfig() as any;
  const hostname = requestHostname(event);
  const routed = routedSubdomain(event);
  // Пріоритет: фіксований магазин через env → X-Subdomain від роутера платформи → Host
  const key = c.storeSubdomain ? `sub:${c.storeSubdomain}` : c.storeDomain ? `dom:${c.storeDomain}` : routed ? `sub:${routed}` : `host:${hostname}`;
  const hit = cache.get(key);
  if (hit && Date.now() - hit.at < hit.ttl) return hit.value;

  let value: ServerStoreConfig | null = null;
  if (c.storeSubdomain) {
    value = await fetchConfig(`/site-template/public/config/subdomain/${encodeURIComponent(c.storeSubdomain)}`);
  } else if (c.storeDomain) {
    value = await fetchConfig(`/site-template/public/config/domain/${encodeURIComponent(c.storeDomain)}`);
  } else if (routed) {
    value = await fetchConfig(`/site-template/public/config/subdomain/${encodeURIComponent(routed)}`);
  } else if (hostname && hostname.includes('.')) {
    const sub = subdomainOf(hostname);
    const base = String(c.public?.storeBaseDomain || '');
    // Піддомен платформи або *.localhost — за піддоменом; інакше — власний домен
    if (sub && (hostname.endsWith('.localhost') || (base && hostname.endsWith('.' + base) && hostname !== 'www.' + base))) {
      value = await fetchConfig(`/site-template/public/config/subdomain/${encodeURIComponent(sub)}`);
    } else {
      value = await fetchConfig(`/site-template/public/config/domain/${encodeURIComponent(hostname)}`);
      if (!value && hostname.startsWith('www.')) {
        value = await fetchConfig(`/site-template/public/config/domain/${encodeURIComponent(hostname.slice(4))}`);
      }
    }
  }
  cache.set(key, { at: Date.now(), ttl: value ? TTL : NEG_TTL, value });
  return value;
};

/** Основний origin магазину для цього запиту. */
export const getStoreOrigin = async (event: any): Promise<string> => {
  const cfg = await getStoreConfig(event);
  const c = useRuntimeConfig() as any;
  return computeStoreOrigin(cfg, String(c.public?.storeBaseDomain || ''), requestHostname(event), requestOrigin(event));
};

/** GET до публічного API магазину з токеном; null при помилці. */
export const storeApi = async <T = any>(cfg: ServerStoreConfig, path: string, params: Record<string, any> = {}): Promise<T | null> => {
  if (!cfg.publicApiToken) return null;
  try {
    return await $fetch<T>(path, { baseURL: apiBase(), params: { token: cfg.publicApiToken, ...params }, timeout: 10000 });
  } catch {
    return null;
  }
};
