using System;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using Serilog;

namespace SharpRSS.API.Models
{
    internal class DbSession
    {
        public DbSession() { }
        private DbSession(string uid, double expiresMinutes)
        {
            if (string.IsNullOrEmpty(uid) || string.IsNullOrWhiteSpace(uid))
            {
                Log.Error("User id is null or empty cannot create session!");
                throw new Exception("User id cannot be null!");
            }
            Uid = uid;
            Created = DateTime.Now;
            Expires = Created.AddMinutes(expiresMinutes);
            string uidHash = Convert.ToHexString(SHA1.HashData(Encoding.UTF8.GetBytes(Uid)));
            string createdHash = Convert.ToHexString(SHA1.HashData(Encoding.UTF8.GetBytes(Created.ToString(CultureInfo.CurrentCulture))));
            Sid = Convert.ToHexString(SHA512.HashData(Encoding.UTF8.GetBytes($"{createdHash}.{uidHash}")));
        }

        public string Uid { get; set; } = string.Empty;
        public string Sid { get; set; } = string.Empty;
        public DateTime Created { get; set; }
        public DateTime Expires { get; set; }

        public bool Expired => Expires < DateTime.Now;

        public DbSession Extend(double extendMinutes = 10080) => new DbSession()
        {
            Uid = Uid,
            Sid = Sid,
            Created = Created,
            Expires = DateTime.Now.AddMinutes(extendMinutes)
        };

        public static DbSession CreateSession(string uid, double expiresMinutes = 10080) => new DbSession(uid, expiresMinutes);
    }
}