using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Service.AppSettingModel;

namespace WebApi.Controllers;

[ApiController]
[Route("api/[controller]/[action]")]
public class AuthController : ControllerBase
{
    private readonly AuthSettings _authSettings;
    private readonly JwtSettings _jwtSettings;
    private readonly ILogger<AuthController> _logger;

    public AuthController(
        IOptions<AuthSettings> authSettings,
        IOptions<JwtSettings> jwtSettings,
        ILogger<AuthController> logger)
    {
        _authSettings = authSettings.Value;
        _jwtSettings = jwtSettings.Value;
        _logger = logger;
    }

    /// <summary>
    /// 用户登录
    /// </summary>
    [AllowAnonymous]
    [HttpPost]
    public BaseResponse<LoginResponse> Login([FromBody] LoginRequest request)
    {
        // 验证密码
        if (string.IsNullOrEmpty(request.Password) || request.Password != _authSettings.Password)
        {
            _logger.LogWarning("登录失败: 密码错误");
            return "密码错误".Fail<LoginResponse>();
        }

        // 生成JWT Token
        var token = GenerateJwtToken();
        var expiresAt = DateTime.UtcNow.AddHours(_jwtSettings.ExpirationHours);

        _logger.LogInformation("用户登录成功");

        return new LoginResponse
        {
            Token = token,
            ExpiresAt = expiresAt
        }.Ok();
    }

    private string GenerateJwtToken()
    {
        var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.SecretKey));
        var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

        var claims = new[]
        {
            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
            new Claim(JwtRegisteredClaimNames.Iat, DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString()),
            new Claim("auth", "password-auth")
        };

        var token = new JwtSecurityToken(
            issuer: _jwtSettings.Issuer,
            audience: _jwtSettings.Audience,
            claims: claims,
            expires: DateTime.UtcNow.AddHours(_jwtSettings.ExpirationHours),
            signingCredentials: credentials
        );

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