import { NextRequest, NextResponse } from 'next/server';
import {
  findDomainForLocale,
  getSnippetsForLocale,
  getSnippetsForSnippetSetId,
  isAdminApiConfigured,
} from '@/lib/shopware-admin';

/**
 * GET /api/snippets?locale=de-DE
 *
 * Returns the merged storefront snippet set for the current domain as a flat
 * { "dotted.key": "value" } map. Resolves the snippet set in this priority:
 *   1. Sales-channel domain matching the request's origin (admin-configured)
 *   2. Snippet set whose `iso` matches the locale query param
 *
 * Server-side proxy so Admin API credentials never reach the browser. Returns
 * an empty map (200) when admin isn't configured so the UI degrades gracefully.
 */

const LOCALE_RE = /^[a-z]{2}-[A-Z]{2}$/;

export async function GET(request: NextRequest) {
  const locale = request.nextUrl.searchParams.get('locale') || '';

  if (!LOCALE_RE.test(locale)) {
    return NextResponse.json({ error: 'Invalid locale' }, { status: 400 });
  }

  if (!isAdminApiConfigured()) {
    return NextResponse.json({ locale, snippets: {} });
  }

  try {
    // Build the origin Shopware stores in Admin → Domains (e.g. http://localhost:3000).
    const host = request.headers.get('host') || '';
    const proto =
      request.headers.get('x-forwarded-proto') ||
      (host.startsWith('localhost') ? 'http' : 'https');
    const origin = host ? `${proto}://${host}` : '';

    let snippets: Record<string, string> = {};
    if (origin) {
      // Disambiguate path-prefixed domains (…/en-GB vs …/de-DE) by the locale.
      const domain = await findDomainForLocale(origin, locale);
      if (domain?.snippetSetId) {
        snippets = await getSnippetsForSnippetSetId(domain.snippetSetId);
      }
    }
    if (Object.keys(snippets).length === 0) {
      snippets = await getSnippetsForLocale(locale);
    }

    return NextResponse.json(
      { locale, snippets },
      {
        headers: {
          'Cache-Control':
            'public, max-age=600, s-maxage=600, stale-while-revalidate=86400',
        },
      }
    );
  } catch (e) {
    console.error('Failed to load snippets:', e);
    return NextResponse.json({ locale, snippets: {} });
  }
}
