namespace RpgRoller.Api;

internal static class SessionTokenHttpContextExtensions
{
    public static bool TryReadSessionTokenFromCookie(this HttpContext context, out string sessionToken)
    {
        sessionToken = context.Request.Cookies[SessionCookie.Name] ?? string.Empty;
        return !string.IsNullOrWhiteSpace(sessionToken);
    }

    public static void StoreSessionToken(this HttpContext context, string sessionToken)
    {
        context.Items[SessionTokenItemKey] = sessionToken;
    }

    public static string GetRequiredSessionToken(this HttpContext context)
    {
        if (context.Items.TryGetValue(SessionTokenItemKey, out var token) && token is string sessionToken && !string.IsNullOrWhiteSpace(sessionToken))
            return sessionToken;

        throw new InvalidOperationException("Session token is not available in this request.");
    }

    private const string SessionTokenItemKey = "__rpgroller.session-token";
}