/**
 * JSON-снапшот магазину з диска (його пише crm-market-back у STORE_SNAPSHOT_DIR).
 * Пошук файла: фіксований магазин з env → хост запиту (X-Forwarded-Host → X-Subdomain+base → Host)
 * → by-subdomain/<sub>.json. Кеш у пам'яті з перевіркою mtime через fs.stat.
 * Немає директорії/файла, битий JSON або інша версія → null, і шаблон працює через API як раніше.
 */
import { promises as fs } from 'node:fs';
import { join, resolve, sep } from 'node:path';
import {
  indexStoreSnapshot,
  isStoreSnapshotData,
  type LoadedStoreSnapshot,
} from '../../utils/store-snapshot-query';
import { requestHostname, routedSubdomain, hostSubdomain } from './store-config';

/** Як часто перевіряти mtime одного файла (усередині одного SSR-запиту stat не повторюється). */
const STAT_INTERVAL = 1000;
/** Максимум розібраних снапшотів у пам'яті (по одному на магазин). */
const MAX_CACHED = 100;

interface CacheEntry {
  checkedAt: number;
  mtimeMs: number;
  size: number;
  snap: LoadedStoreSnapshot | null;
}

const cache = new Map<string, CacheEntry>();

const LABEL = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;

/** Те саме правило, що й safeHostName на беку: лише валідні DNS-мітки (захист від ../ у шляху). */
const safeHost = (raw?: string | null): string | null => {
  const host = String(raw ?? '').trim().toLowerCase().replace(/:\d+$/, '').replace(/\.$/, '');
  if (!host || host.length > 253) return null;
  return host.split('.').every((l) => LABEL.test(l)) ? host : null;
};

const safeSub = (raw?: string | null): string | null => {
  const s = safeHost(raw);
  return s && !s.includes('.') ? s : null;
};

/** Директорія снапшотів: runtimeConfig.storeSnapshotDir (NUXT_STORE_SNAPSHOT_DIR) або STORE_SNAPSHOT_DIR у рантаймі. */
export const storeSnapshotDir = (): string => {
  const c = useRuntimeConfig() as any;
  return String(c.storeSnapshotDir || process.env.STORE_SNAPSHOT_DIR || '').trim();
};

/** Відносні шляхи файлів-кандидатів для запиту (за пріоритетом). */
export const snapshotCandidates = (event: any): string[] => {
  const c = useRuntimeConfig() as any;
  const out: string[] = [];
  const add = (rel: string | null) => {
    if (rel && !out.includes(rel)) out.push(rel);
  };
  const fixedSub = safeSub(c.storeSubdomain);
  const fixedDomain = safeHost(c.storeDomain);
  if (fixedSub) add(`by-subdomain/${fixedSub}.json`);
  if (fixedDomain) add(`${fixedDomain}.json`);
  if (fixedSub || fixedDomain) return out;

  const host = safeHost(requestHostname(event));
  if (host) add(`${host}.json`);
  const sub = safeSub(routedSubdomain(event)) || safeSub(host ? hostSubdomain(host) : null);
  if (sub) add(`by-subdomain/${sub}.json`);
  return out;
};

const loadFile = async (abs: string): Promise<LoadedStoreSnapshot | null> => {
  const now = Date.now();
  const hit = cache.get(abs);
  if (hit && now - hit.checkedAt < STAT_INTERVAL) return hit.snap;

  let st: { mtimeMs: number; size: number };
  try {
    st = await fs.stat(abs); // stat іде за symlink → mtime канонічного файла
  } catch {
    cache.set(abs, { checkedAt: now, mtimeMs: -1, size: -1, snap: null });
    return null;
  }
  if (hit && hit.mtimeMs === st.mtimeMs && hit.size === st.size) {
    hit.checkedAt = now;
    return hit.snap;
  }

  let snap: LoadedStoreSnapshot | null = null;
  try {
    const raw = JSON.parse(await fs.readFile(abs, 'utf8'));
    if (isStoreSnapshotData(raw)) snap = indexStoreSnapshot(raw, abs);
    else console.warn(`[store-snapshot] ${abs}: невідома версія або форма файла — працюємо через API`);
  } catch (e: any) {
    console.warn(`[store-snapshot] ${abs}: не вдалося прочитати (${e?.message || e}) — працюємо через API`);
  }
  cache.delete(abs);
  if (cache.size >= MAX_CACHED) cache.delete(cache.keys().next().value as string);
  cache.set(abs, { checkedAt: now, mtimeMs: st.mtimeMs, size: st.size, snap });
  return snap;
};

/** Снапшот магазину для запиту; null — немає (тоді все йде через API). Мемоізується на запит. */
export const getStoreSnapshot = (event: any): Promise<LoadedStoreSnapshot | null> => {
  const ctx = event?.context;
  if (ctx && ctx.__storeSnapshot) return ctx.__storeSnapshot;
  const run = (async () => {
    const dir = storeSnapshotDir();
    if (!dir) return null;
    const root = resolve(dir);
    for (const rel of snapshotCandidates(event)) {
      const abs = join(root, rel);
      if (!abs.startsWith(root + sep)) continue;
      const snap = await loadFile(abs);
      if (snap) return snap;
    }
    return null;
  })();
  if (ctx) ctx.__storeSnapshot = run;
  return run;
};
