'use server'
import {createCanvas} from 'canvas'
import crypto from 'crypto'
import {cookies} from 'next/headers'

// 生成随机验证码
function generateCaptchaText(length: number = 4): string {
  const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  let result = ''
  for (let i = 0; i < length; i++) {
    result += chars[Math.floor(Math.random() * chars.length)]
  }
  return result
}

// 哈希验证码文本并使用随机盐值
function hashCaptcha(text: string): {hash: string, salt: string} {
  const salt = crypto.randomBytes(16).toString('hex')
  const hash = crypto
    .createHmac('sha256', salt)
    .update(text.toLowerCase())
    .digest('hex')
  return {hash, salt}
}

// 生成验证码图片
function generateCaptchaImage(text: string) {
  const canvas = createCanvas(180, 50)
  const ctx = canvas.getContext('2d')

  // 设置背景色
  ctx.fillStyle = '#f3f4f6'
  ctx.fillRect(0, 0, 180, 50)

  // 绘制干扰线
  for (let i = 0; i < 3; i++) {
    ctx.strokeStyle = `rgb(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255})`
    ctx.beginPath()
    ctx.moveTo(Math.random() * 180, Math.random() * 50)
    ctx.lineTo(Math.random() * 180, Math.random() * 50)
    ctx.stroke()
  }

  // 绘制文本
  ctx.font = '28px sans-serif'
  ctx.textAlign = 'center'
  ctx.textBaseline = 'middle'

  // 随机文本颜色和位置
  for (let i = 0; i < text.length; i++) {
    ctx.fillStyle = `rgb(${Math.random() * 100}, ${Math.random() * 100}, ${Math.random() * 100})`
    ctx.fillText(
      text[i],
      (180 / text.length) * (i + 0.5), // 均匀分布
      25 + Math.random() * 10 - 5, // 中间位置上下浮动
    )
  }

  return canvas.toBuffer('image/png')
}

export async function GET(request: Request) {
  const captchaText = generateCaptchaText()
  console.log('生成验证码:', captchaText)

  // 生成验证码图像
  const captchaImage = generateCaptchaImage(captchaText)

  // 生成验证码哈希和盐值
  const {hash, salt} = hashCaptcha(captchaText)
  const store = await cookies()
  const coo = store
    .set('captcha_hash', hash, {
      httpOnly: true,
      sameSite: 'strict',
      maxAge: 60,
    })
    .set('captcha_salt', salt, {
      httpOnly: true,
      sameSite: 'strict',
      maxAge: 60,
    })

  return new Response(new ReadableStream({
    start(controller) {
      controller.enqueue(captchaImage)
      controller.close()
    },
  }), {
    headers: {
      'Content-Type': 'image/png',
      'Cache-Control': 'no-store',
      'Set-Cookie': `${coo}`,
    },
  })
}
