using Fuel.Application.Service;
using Fuel.Core;
using Fuel.Core.User;
using Fuel.Core.WechatServer;
using FuelServer.Core;
using FuelServer.Core.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using System.IdentityModel.Tokens.Jwt;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Text;

namespace Fuel.PaymentServer.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AuthController : ControllerBase
    {
        private readonly IUserService _userService;
        private readonly IConfiguration _configuration;
        private readonly ISiteService _siteService;

        public AuthController(IUserService userService, IConfiguration configuration, ISiteService siteService)
        {
            _userService = userService;
            _configuration = configuration;
            _siteService = siteService;
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="login"></param>
        /// <returns></returns>
        [HttpGet("login")]
        public IActionResult Login([FromBody] LoginModel login)
        {
            var user = _userService.ValidateCredentials(login.Username, login.Password);
            if (user == null)
                return Unauthorized();

            var tokenString = GenerateJwt(user);
            return Ok(new { Token = tokenString });
        }
        /// <summary>
        /// 小程序登录
        /// </summary>
        /// <param name="login"></param>
        /// <returns></returns>
        [HttpGet("Wechatlogin")]
        public async Task<IActionResult> Wechatlogin(string code)
        {
            Guid Buid = HttpRequestReader.GetCurrentBuId(); //站点id
            Guid WachatID = HttpRequestReader.GetWachatID(); //小程序用户id
            var appidResponse = await _siteService.GetAppidSecret(code);
            if (!appidResponse.IsSuccessful())
            {
                return StatusCode((int)appidResponse.StatusCode, appidResponse.Message);
            }
            return Ok(appidResponse);
        }



        private string GenerateJwt(users user)
        {
            var jwtSettings = ConstKey.JwtKey;
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
                new Claim(JwtRegisteredClaimNames.Email, user.Account),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
            };

            var token = new JwtSecurityToken(
                issuer: ConstKey.JwtIssuer,
                audience: ConstKey.JwtAudience,
                claims: claims,
                expires: DateTime.Now.AddMinutes(15),
                signingCredentials: credentials
            );

            return new JwtSecurityTokenHandler().WriteToken(token);
        }
    }
}
