using DataSharing.Application.Identity;
using DataSharing.Share.Dtos;
using DataSharing.Share.Dtos.Province;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using XF.Domain.Filters;
using XF.Domain.Options;

namespace DataSharing.Host.Controllers
{
    public class AccountController : BaseController
    {
        private readonly IIdentityAppService _identityAppService;
        private readonly IOptionsSnapshot<IdentityConfiguration> _identityOptionsAccessor;

        public AccountController(IIdentityAppService identityAppService,
        IOptionsSnapshot<IdentityConfiguration> identityOptionsAccessor)
        {
            _identityAppService = identityAppService;
            _identityOptionsAccessor = identityOptionsAccessor;
        }

        /// <summary>
        /// 根据账号、秘钥获取token授权
        /// </summary>
        /// <param name="ClientID">账号</param>
        /// <param name="Secret">密码</param>
        /// <returns></returns>
        [HttpGet("api/token")]
        [AllowAnonymous]
        public async Task<OpenResponse> GetTokenProvince(string ClientID, string Secret)
        {
            var token = await _identityAppService.LoginTokenAsync(new LoginDto() { Username = ClientID, Password = Secret }, HttpContext.RequestAborted);

            if (token == null || !token.IsSuccess)
                return OpenResponse.Ok(GetDataBaseReponse<ProvinceTokenInfo>.Failed(token?.Message));

            var jwtOptions = _identityOptionsAccessor.Value.Jwt;
            ProvinceTokenInfo tokenInfo = new()
            {
                ExpiresIn = jwtOptions.Expired,
                Token = token.Token
            };

            return OpenResponse.Ok(GetDataBaseReponse<ProvinceTokenInfo>.Success(tokenInfo, "授权成功"));
        }
    }
}
