import { NextResponse } from 'next/server';
import '@/lib/shopware-server-init';
import { getCmsPage } from '@/lib/shopware-api';
import { getShopPageCmsId, type ShopPageKey } from '@/lib/shopware-admin';

export const dynamic = 'force-dynamic';

const FALLBACK_TITLES: Record<string, string> = {
  tos: 'Terms and conditions',
  revocation: 'Right of withdrawal',
  privacy: 'Privacy',
  imprint: 'Imprint',
  shippingPayment: 'Payment / Shipping',
};

const VALID_KEYS: ShopPageKey[] = ['tos', 'revocation', 'privacy', 'imprint', 'shippingPayment'];

/** Concatenate the HTML of every text/html slot on a CMS page. */
function extractCmsHtml(page: any): string {
  const sections = page?.sections?.elements ?? page?.sections ?? [];
  const parts: string[] = [];
  for (const section of sections) {
    const blocks = section?.blocks?.elements ?? section?.blocks ?? [];
    for (const block of blocks) {
      const slots = block?.slots?.elements ?? block?.slots ?? [];
      for (const slot of slots) {
        const type = (slot?.type ?? '').replace(/^cms[-_]/, '');
        if (type === 'text' || type === 'html') {
          const content = slot?.data?.content ?? slot?.config?.content?.value;
          if (content) parts.push(content);
        }
      }
    }
  }
  return parts.join('\n');
}

export async function GET(req: Request) {
  const url = new URL(req.url);
  const keyParam = url.searchParams.get('key') ?? 'tos';
  const key = (VALID_KEYS.includes(keyParam as ShopPageKey) ? keyParam : 'tos') as ShopPageKey;

  try {
    const pageId = await getShopPageCmsId(key);
    if (!pageId) {
      return NextResponse.json({ html: null, title: FALLBACK_TITLES[key] });
    }
    const page = await getCmsPage(pageId);
    const html = extractCmsHtml(page);
    const title = (page as any)?.name || FALLBACK_TITLES[key];
    return NextResponse.json({ title, html: html || null });
  } catch (e: any) {
    return NextResponse.json(
      { html: null, title: FALLBACK_TITLES[key], error: e?.message ?? String(e) },
      { status: 200 }
    );
  }
}
