using System.Security.Claims;
using Yuna.Website.Server.Model;

namespace Yuna.Website.Server.Infrastructure
{
    public static class CookieExtensions
    {
        public static T LoadFromCookies<T>(this HttpContext context, string key)
        {
            if (context.Request.Cookies.TryGetValue(key, out var value))
            {
                try
                {
                    return System.Text.Json.JsonSerializer.Deserialize<T>(value)
                        ?? throw new Exception();
                }

                catch
                {
                    return default!;
                }
            }

            return default!;
        }

        public static void SaveToCookies<T>(this HttpContext context, string key, T value, TimeSpan? maxAge = null)
        {
            var dataStr = System.Text.Json.JsonSerializer.Serialize<T>(value);

            if (context.Request.Cookies.ContainsKey(key)) context.Response.Cookies.Delete(key);

            context.Response.Cookies.Append(key, dataStr, new CookieOptions() { HttpOnly = true, MaxAge = maxAge ?? TimeSpan.FromDays(365) });
        }

        public static long? GetUserIdFromCookie(this HttpContext context)
        {
            var idStr = context.User.FindFirstValue(ClaimTypes.NameIdentifier);
            var isParsed = long.TryParse(idStr, out var result);
            return isParsed ? result : null;
        }

        public static bool GetRoleFromCookie(this HttpContext context)
        {
            if (bool.TryParse(context.User.FindFirstValue(ClaimTypes.Role), out var result))
            {
                return result;
            }
            return false;
        }

    }
}
