<?php
declare (strict_types=1);

namespace app\service\util;

use think\captcha\facade\Captcha;

/**
 * @author canny
 * @date 2024/1/3 16:06
 **/
class CaptchaUtil
{
    const CAPTCHA_CACHE_KEY = 'captcha:';
    const CACHE_TTL = 1800;

    public static function create($sceneConfig = ''): array
    {
        $res = Captcha::create($sceneConfig);
        $base64Image = 'data:image/png;base64,' . base64_encode($res->getData());
        $key = session('captcha.key');
        $uuid = uniqid();
        RedisService::getRedisInstance()->set(self::getKey($uuid), $key, 'ex', self::CACHE_TTL);
        return ['uuid' => $uuid, 'img' => $base64Image];
    }

    public static function check($uuid, $code): bool
    {
        $redis = RedisService::getRedisInstance();
        $key = $redis->get(self::getKey($uuid));
        if (empty($key)) {
            return false;
        }
        $code = mb_strtolower($code, 'UTF-8');

        $res = password_verify($code, $key);
        if ($res) {
            $redis->del(self::getKey($uuid));
        }

        return $res;
    }

    private static function getKey($uuid): string
    {
        return self::CAPTCHA_CACHE_KEY . $uuid;
    }
}