// iyixiGames.Web/Services/AuthService.cs
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using iyixiGames.Application.Services;
using iyixiGames.Domain.DTOs.Auth; // 引用 Application 层的 IUserService
using iyixiGames.Domain.Entities;
using iyixiGames.Infrastructure.Services;

namespace iyixiGames.Web.Services
{
    public class AuthService : IAuthService
    {
        private readonly IConfiguration _configuration;
        private readonly IUserService _userService;

        public AuthService(IConfiguration configuration, IUserService userService)
        {
            _configuration = configuration;
            _userService = userService;
        }

        public string GenerateJwtToken(User user)
        {
            var jwtSettings = _configuration.GetSection("JwtSettings");
            var secret = jwtSettings["Secret"];
            var issuer = jwtSettings["Issuer"];
            var audience = jwtSettings["Audience"];
            var expiresInMinutes = double.Parse(jwtSettings["ExpiresInMinutes"] ?? "60");

            var key = Encoding.UTF8.GetBytes(secret ?? throw new InvalidOperationException("JWT Secret not configured."));

            var claims = new[]
            {
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.Name, user.Username),
                // 可以添加其他声明，例如用户的角色或权限
                // new Claim(ClaimTypes.Role, "Admin")
            };

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(claims),
                Expires = DateTime.UtcNow.AddMinutes(expiresInMinutes),
                Issuer = issuer,
                Audience = audience,
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };

            var tokenHandler = new JwtSecurityTokenHandler();
            var token = tokenHandler.CreateToken(tokenDescriptor);
            return tokenHandler.WriteToken(token);
        }

        public async Task<LoginResponse> AuthenticateUserAsync(LoginRequest request)
        {
            var loginResult = await _userService.LoginAsync(request);

            if (loginResult.Success && loginResult.UserId > 0)
            {
                var user = await _userService.GetUserByUsernameAsync(request.Username);
                if (user != null)
                {
                    loginResult.Token = GenerateJwtToken(user);
                }
            }
            return loginResult;
        }
    }
}