/**
 * ============================================
 * SERVER-SIDE SNIPPET HELPER
 * ============================================
 * Async equivalent of useTranslation() for server components. Pulls the
 * merged snippet set for the active locale and returns a sync `t(key, fallback)`.
 *
 *   const { t } = await getServerSnippets();
 *   <p>{t('footer.serviceHotlineHeadline', 'Service hotline')}</p>
 *
 * Uses the same Shopware snippet keys the default Twig storefront uses, so
 * keys translated in Admin → Settings → Snippets carry over for free.
 */

import { cookies, headers } from 'next/headers';
import {
  findDomainForLocale,
  getSnippetsForLocale,
  getSnippetsForSnippetSetId,
  isAdminApiConfigured,
} from './shopware-admin';

const DEFAULT_LOCALE = process.env.NEXT_PUBLIC_LOCALE || 'en-GB';
const LOCALE_RE = /^[a-z]{2}-[A-Z]{2}$/;

export interface ServerSnippets {
  locale: string;
  t: (key: string, fallback?: string) => string;
}

/**
 * Build the current request's origin (protocol + host) from forwarded headers,
 * matching the URL format Shopware stores in Admin → Sales Channels → Domains.
 * Returns null if we're not inside a request scope.
 */
function getRequestOrigin(): string | null {
  try {
    const h = headers();
    const host = h.get('host');
    if (!host) return null;
    // Locale prefix is stripped by middleware before we get here, so host is
    // the bare domain (e.g. "localhost:3000") — exactly what's stored in
    // admin for the URL field.
    const proto = h.get('x-forwarded-proto') || (host.startsWith('localhost') ? 'http' : 'https');
    return `${proto}://${host}`;
  } catch {
    return null;
  }
}

export async function getServerSnippets(): Promise<ServerSnippets> {
  let locale = DEFAULT_LOCALE;
  try {
    const fromCookie = cookies().get('sw-locale')?.value;
    if (fromCookie && LOCALE_RE.test(fromCookie)) locale = fromCookie;
  } catch {
    // Outside a request scope (build-time prerender) — fall back to default.
  }

  let snippets: Record<string, string> = {};
  if (isAdminApiConfigured()) {
    try {
      // Prefer the snippet set assigned to THIS domain in admin (authoritative).
      const origin = getRequestOrigin();
      if (origin) {
        // Locale disambiguates path-prefixed domains that share a host.
        const domain = await findDomainForLocale(origin, locale);
        if (domain?.snippetSetId) {
          snippets = await getSnippetsForSnippetSetId(domain.snippetSetId);
        }
      }
      // Fallback: pick whichever snippet set matches the cookie locale.
      if (Object.keys(snippets).length === 0) {
        snippets = await getSnippetsForLocale(locale);
      }
    } catch {
      // Admin API down → degrade to hardcoded fallbacks.
    }
  }

  return {
    locale,
    t: (key, fallback) => snippets[key] ?? fallback ?? key,
  };
}
