import { NextResponse } from 'next/server'
import { createHmac } from 'crypto'

const SECRET = process.env.CAPTCHA_SECRET ?? 'sterowniki-captcha-secret-change-in-env'

function rand(min: number, max: number) {
  return Math.floor(Math.random() * (max - min + 1)) + min
}

export async function GET() {
  const a = rand(2, 15)
  const b = rand(1, 12)
  const useAdd = Math.random() > 0.4
  let answer: number
  let display: string

  if (useAdd) {
    answer = a + b
    display = `${a} + ${b}`
  } else {
    const big = Math.max(a, b)
    const small = Math.min(a, b)
    answer = big - small
    display = `${big} - ${small}`
  }

  const token = createHmac('sha256', SECRET).update(String(answer)).digest('hex')

  const lines = Array.from({ length: 5 }, () => {
    const x1 = rand(0, 220); const y1 = rand(0, 70)
    const x2 = rand(0, 220); const y2 = rand(0, 70)
    const op = (rand(25, 55) / 100).toFixed(2)
    return `<line x1="${x1}" y1="${y1}" x2="${x2}" y2="${y2}" stroke="#7dd3fc" stroke-width="1.2" opacity="${op}"/>`
  }).join('')

  const dots = Array.from({ length: 18 }, () => {
    const cx = rand(8, 212); const cy = rand(8, 62); const r = rand(1, 2)
    return `<circle cx="${cx}" cy="${cy}" r="${r}" fill="#38bdf8" opacity="0.35"/>`
  }).join('')

  // Slightly offset letters to make OCR harder
  const chars = (display + ' = ?').split('')
  const textEls = chars.map((ch, i) => {
    const x = 18 + i * 18
    const y = 42 + rand(-4, 4)
    const rot = rand(-8, 8)
    return `<text x="${x}" y="${y}" font-size="24" font-family="Courier New,monospace" fill="#1e40af" font-weight="bold" transform="rotate(${rot},${x},${y})">${ch}</text>`
  }).join('')

  const svg = `<svg width="220" height="70" xmlns="http://www.w3.org/2000/svg">
<rect width="220" height="70" fill="#f0f9ff" rx="8" stroke="#bae6fd" stroke-width="1.5"/>
${lines}${dots}${textEls}
</svg>`

  return NextResponse.json({ svg, token }, {
    headers: { 'Cache-Control': 'no-store, no-cache, must-revalidate' }
  })
}
