using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Meezi.Core.Constants;
using Meezi.Core.Entities;
using Microsoft.IdentityModel.Tokens;

namespace Meezi.Admin.API.Services;

public interface IAdminJwtTokenService
{
    string CreateAdminAccessToken(SystemAdmin admin);
    string CreateRefreshToken();
    DateTime GetAccessTokenExpiry();
}

public class AdminJwtTokenService : IAdminJwtTokenService
{
    private readonly IConfiguration _configuration;

    public AdminJwtTokenService(IConfiguration configuration) => _configuration = configuration;

    public string CreateAdminAccessToken(SystemAdmin admin)
    {
        var key = _configuration["Jwt:Key"] ?? throw new InvalidOperationException("Jwt:Key is not configured.");
        var issuer = _configuration["Jwt:Issuer"] ?? "meezi";
        var audience = _configuration["Jwt:Audience"] ?? "meezi-admin";
        var expiryDays = _configuration.GetValue("Jwt:AccessTokenExpiryDays", 7);

        var claims = new List<Claim>
        {
            new(JwtRegisteredClaimNames.Sub, admin.Id),
            new(ClaimTypes.Role, "SystemAdmin"),
            new(MeeziClaimTypes.Role, "SystemAdmin"),
            new(MeeziClaimTypes.Actor, MeeziActorKinds.SystemAdmin),
            new(MeeziClaimTypes.Language, "fa"),
            new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N"))
        };

        var credentials = new SigningCredentials(
            new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key)),
            SecurityAlgorithms.HmacSha256);

        var token = new JwtSecurityToken(
            issuer,
            audience,
            claims,
            expires: DateTime.UtcNow.AddDays(expiryDays),
            signingCredentials: credentials);

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

    public string CreateRefreshToken() => Guid.NewGuid().ToString("N") + Guid.NewGuid().ToString("N");

    public DateTime GetAccessTokenExpiry()
    {
        var expiryDays = _configuration.GetValue("Jwt:AccessTokenExpiryDays", 7);
        return DateTime.UtcNow.AddDays(expiryDays);
    }
}
