import { NextRequest, NextResponse } from 'next/server';
import { getStorefrontSecuritySettings } from '@/lib/shopware-admin';
import { verifyCaptcha, clientIpFromHeaders } from '@/lib/captcha-server';
import { CAPTCHA_PAYLOAD_KEYS, type CaptchaPayload } from '@/lib/captcha-types';

const SHOPWARE_URL = process.env.NEXT_PUBLIC_SHOPWARE_URL || '';
const ACCESS_KEY = process.env.NEXT_PUBLIC_SHOPWARE_ACCESS_KEY || '';

export async function POST(request: NextRequest) {
  let body: Record<string, any>;
  try {
    body = await request.json();
  } catch {
    return NextResponse.json({ error: 'Invalid request body.' }, { status: 400 });
  }

  // 1. Validate whichever CAPTCHAs the merchant activated in admin.
  const captchaPayload: CaptchaPayload = {};
  const formData: Record<string, any> = {};
  for (const [key, val] of Object.entries(body)) {
    if ((CAPTCHA_PAYLOAD_KEYS as string[]).includes(key)) {
      (captchaPayload as any)[key] = val;
    } else {
      formData[key] = val;
    }
  }
  const captchaResult = await verifyCaptcha(captchaPayload, clientIpFromHeaders(request.headers));
  if (!captchaResult.valid) {
    return NextResponse.json(
      { error: captchaResult.error || 'Captcha verification failed.' },
      { status: 400 }
    );
  }

  // 2. Enforce admin-configured required fields up front (clearer message than
  // the generic Store API violation, and saves a round-trip). Shopware still
  // re-validates these server-side as the source of truth.
  const security = await getStorefrontSecuritySettings();
  const requiredFields: Array<[keyof typeof formData, boolean, string]> = [
    ['firstName', security.firstNameFieldRequired, 'First name'],
    ['lastName', security.lastNameFieldRequired, 'Last name'],
    ['phone', security.phoneNumberFieldRequired, 'Phone number'],
  ];
  for (const [field, isRequired, label] of requiredFields) {
    if (isRequired && !String(formData[field] ?? '').trim()) {
      return NextResponse.json({ error: `${label} is required.` }, { status: 400 });
    }
  }

  // 3. Forward to Shopware Store API
  const contextToken = request.headers.get('sw-context-token') || '';
  const shopwareHeaders: Record<string, string> = {
    'Content-Type': 'application/json',
    Accept: 'application/json',
    'sw-access-key': ACCESS_KEY,
  };
  if (contextToken) shopwareHeaders['sw-context-token'] = contextToken;

  const shopwareRes = await fetch(`${SHOPWARE_URL}/store-api/contact-form`, {
    method: 'POST',
    headers: shopwareHeaders,
    body: JSON.stringify(formData),
    cache: 'no-store',
  });

  if (!shopwareRes.ok) {
    const err = await shopwareRes.json().catch(() => ({}));
    return NextResponse.json(
      { error: err.errors?.[0]?.detail || `Shopware error: ${shopwareRes.status}` },
      { status: shopwareRes.status }
    );
  }

  // 204 No Content = success
  return NextResponse.json({ success: true }, { status: 200 });
}
