using System;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using MyHN.Application;

namespace Api
{
  public class UserNotConnected : Exception
  {

  }

  public class HttpUserProvider : IUserProvider
  {
    private readonly IHttpContextAccessor _httpContextAccessor;
    private readonly UserManager<IdentityUser> _userManager;

    public HttpUserProvider(
        IHttpContextAccessor httpContextAccessor
      , UserManager<IdentityUser> userManager)
    {
      _httpContextAccessor = httpContextAccessor;
      _userManager = userManager;
    }

    public string GetCurrentUserId()
    {
      var userid = _userManager.GetUserId(_httpContextAccessor.HttpContext.User);

      if (string.IsNullOrWhiteSpace(userid))
      {
        throw new UserNotConnected();
      }

      return userid;
    }
  }
}