namespace SummerBestWebForm2.SessionState;

// INTERFACE

public interface ISessionIdManager
{
  Task<string?> GetSessionIdAsync();
  Task<string?> GetIPAddressAsync();
}

// CODE

public class SessionIdManager(IHttpContextAccessor httpContextAccessor) : ISessionIdManager
{
  private readonly IHttpContextAccessor HttpContextAccessor = httpContextAccessor;

  public Task<string?> GetSessionIdAsync()
  {
    var httpContext = HttpContextAccessor.HttpContext;
    string? result;

    if (httpContext != null)
    {
      if (httpContext.Request.Cookies.ContainsKey("sessionId"))
      {
        result = httpContext.Request.Cookies["sessionId"];
      }
      else
      {
        result = Guid.NewGuid().ToString();
        httpContext.Response.Cookies.Append("sessionId", result);
      }
    }
    else
    {
      throw new InvalidOperationException("No HttpContext available");
    }
    return Task.FromResult(result);
  }

  public Task<string?> GetIPAddressAsync()
  {
    var httpContext = HttpContextAccessor.HttpContext;
    string? result;

    if (httpContext != null)
    {
      result = httpContext.Connection.RemoteIpAddress?.ToString();// ?? "Not Set";
    }
    else
    {
      throw new InvalidOperationException("No HttpContext available");
    }
    return Task.FromResult(result);
  }

}
