import { NextResponse } from 'next/server';
import { signBasicAnswer } from '@/lib/captcha-server';

export const dynamic = 'force-dynamic';

/**
 * Basic (image) CAPTCHA challenge generator — the headless equivalent of
 * Shopware's "Basic Captcha". Returns an SVG math puzzle plus an HMAC-signed
 * token of the answer, so verification is stateless (see captcha-server.ts).
 * Only rendered when Basic Captcha is active in admin.
 */

/** Build a simple SVG image that looks like a captcha */
function buildCaptchaSvg(text: string): string {
  const width = 160;
  const height = 50;

  // Random noise lines for visual distortion
  const lines = Array.from({ length: 6 }, () => {
    const x1 = Math.random() * width;
    const y1 = Math.random() * height;
    const x2 = Math.random() * width;
    const y2 = Math.random() * height;
    const color = `hsl(${Math.random() * 360},50%,60%)`;
    return `<line x1="${x1.toFixed(0)}" y1="${y1.toFixed(0)}" x2="${x2.toFixed(0)}" y2="${y2.toFixed(0)}" stroke="${color}" stroke-width="1.5"/>`;
  }).join('');

  // Each character rendered with slight rotation and offset
  const chars = text.split('').map((ch, i) => {
    const x = 18 + i * 22;
    const y = 32 + (Math.random() * 8 - 4);
    const rotate = Math.random() * 20 - 10;
    const hue = Math.floor(Math.random() * 60); // dark blues/greens
    const color = `hsl(${hue},60%,30%)`;
    return `<text x="${x}" y="${y.toFixed(1)}" transform="rotate(${rotate.toFixed(1)},${x},${y.toFixed(1)})" fill="${color}" font-size="22" font-family="monospace" font-weight="bold">${ch}</text>`;
  }).join('');

  return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" style="background:#f3f4f6;border-radius:4px;">${lines}${chars}</svg>`;
}

export async function GET() {
  const a = Math.floor(Math.random() * 9) + 1;
  const b = Math.floor(Math.random() * 9) + 1;
  const answer = String(a + b);
  const token = signBasicAnswer(answer);

  // Display as "3 + 7 = ?" with some padding chars for visual noise
  const displayText = `${a} + ${b} = ?`;
  const svg = buildCaptchaSvg(displayText);
  const imageBase64 = `data:image/svg+xml;base64,${Buffer.from(svg).toString('base64')}`;

  return NextResponse.json({ imageBase64, token });
}
