const express = require('express');
const router = express.Router();
const svgCaptcha = require('svg-captcha');
const { success } = require('../utils/response');

const CAPTCHA_EXPIRE_MS = 5 * 60 * 1000;
const captchaStore = {};

function cleanCaptcha() {
  const now = Date.now();
  for (const key in captchaStore) {
    if (captchaStore[key].expires < now) delete captchaStore[key];
  }
}

router.get('/captcha', (req, res) => {
  const captcha = svgCaptcha.create({
    size: 4, fontSize: 50, width: 120, height: 40,
    noise: 2, color: true, background: '#f0f4ff',
  });
  const id = Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
  captchaStore[id] = {
    text: captcha.text.toLowerCase(),
    expires: Date.now() + CAPTCHA_EXPIRE_MS
  };
  cleanCaptcha();
  res.cookie('captcha_id', id, { maxAge: CAPTCHA_EXPIRE_MS, httpOnly: true, sameSite: 'lax' });
  res.type('svg').send(captcha.data);
});

module.exports = { router, captchaStore, CAPTCHA_EXPIRE_MS };
