using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.IdentityModel.Tokens;

namespace Auth.Services {
    public class AuthJWT {

        public static string TokenAudience = "mistox-llc-auth-token";
        public static string TokenIssuer = "https://auth.mistox.com";
        public static string TokenSecretKey = "";
        public static string TokenName = "mistox_session";

        public static string GenereateJWTToken(int accountID, bool StayLoggedIn) {
            var tokenHandler = new JwtSecurityTokenHandler();
            var key = Encoding.UTF8.GetBytes(TokenSecretKey);

            var tokenDiscriptor = new SecurityTokenDescriptor {
                Subject = new ClaimsIdentity([
                    new Claim(ClaimTypes.NameIdentifier, accountID.ToString()),
                    new Claim(ClaimTypes.IsPersistent, StayLoggedIn.ToString())
                ]),
                Expires = DateTime.UtcNow.AddDays(7),
                IssuedAt = DateTime.UtcNow,
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256),
                Audience = TokenAudience,
                Issuer = TokenIssuer
            };

            var token = tokenHandler.CreateToken(tokenDiscriptor);
            return tokenHandler.WriteToken(token);
        }

        public static void SignIn(HttpResponse Response, bool StayLoggedIn, string jwt) {
            if (StayLoggedIn) {
                // Stay logged in cookie
                Response.Cookies.Append(TokenName, jwt, new CookieOptions {
                    Secure = true,
                    HttpOnly = true,
                    SameSite = SameSiteMode.Strict,
                    Expires = DateTime.UtcNow.AddDays(7)
                });
            } else {
                // Session cookie
                Response.Cookies.Append(TokenName, jwt, new CookieOptions {
                    Secure = true,
                    HttpOnly = true,
                    SameSite = SameSiteMode.Strict,
                });
            }
        }

        public static void SignOut(HttpResponse Response) {
            Response.Cookies.Delete(TokenName);
        }
    }
}