using System;
using System.Threading.Tasks;
using GxPress.Common.Tools;
using GxPress.Result.Captcha;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using GxPress.Common.Extensions;

namespace GxPress.Api.AdminControllers
{
    /// <summary>
    /// 验证码
    /// </summary>
    [Route("api/admin/captcha")]
    [ApiController]
    public class AdminCaptchaController : ControllerBase
    {
        //验证码过期时间
        private readonly IDistributedCache _cache;

        public AdminCaptchaController(IDistributedCache cache) {
            _cache = cache;
        }

        /// <summary>
        /// 获取验证码图片和Guid
        /// </summary>
        [HttpGet("image")]
        public async Task<CaptchaResult> GetCaptchaImage()
        {
            await using var ms = CaptchaHelper.Create(out var code);
            var guid = Guid.NewGuid();
            //将Guid和验证码值存入redis

            await _cache.SetAsync($"captcha:{guid.ToString()}", code, new DistributedCacheEntryOptions
            {
                AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(300)
            });
            var result = new CaptchaResult
            {
                CaptchaImg = Convert.ToBase64String(ms.ToArray()),
                CaptchaGuid = guid
            };
            return result;
        }
    }
}