using Microsoft.AspNetCore.Http.HttpResults;
using RpgRoller.Services;

namespace RpgRoller.Api;

public static class FrontendEntryEndpoints
{
    public static void MapFrontendEntryEndpoints(this IEndpointRouteBuilder app)
    {
        app.MapGet("/", RedirectRootRequest);
    }

    private static RedirectHttpResult RedirectRootRequest(HttpContext context, IGameService game)
    {
        var redirectPath = context.TryReadSessionTokenFromCookie(out var sessionToken) &&
                           game.GetUserBySession(sessionToken) is not null
            ? "/play"
            : "/login";

        return TypedResults.Redirect(context.Request.PathBase.Add(redirectPath).Value!);
    }
}