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

namespace RpgRoller.Api;

internal static class AuthEndpoints
{
    public static RouteGroupBuilder MapAuthEndpoints(this RouteGroupBuilder group)
    {
        group.MapPost("/auth/register", Results<Ok<UserSummary>, BadRequest<ApiError>> (RegisterRequest request, IGameService game) =>
        {
            var result = game.Register(request.Username, request.Password, request.DisplayName);
            if (!result.Succeeded)
                return ApiResultMapper.ToBadRequest(result.Error!);

            return TypedResults.Ok(result.Value!);
        });

        group.MapPost("/auth/login", Results<Ok<UserSummary>, BadRequest<ApiError>> (LoginRequest request, HttpContext context, IGameService game) =>
        {
            var result = game.Login(request.Username, request.Password);
            if (!result.Succeeded)
                return ApiResultMapper.ToBadRequest(result.Error!);

            context.Response.Cookies.Append(SessionCookie.Name, result.Value.SessionToken, new()
            {
                HttpOnly = true,
                SameSite = SameSiteMode.Strict,
                IsEssential = true,
                Secure = context.Request.IsHttps
            });

            return TypedResults.Ok(result.Value.User);
        });

        group.MapPost("/auth/logout", (HttpContext context, IGameService game) =>
        {
            if (context.TryReadSessionTokenFromCookie(out var sessionToken))
                game.Logout(sessionToken);

            context.Response.Cookies.Delete(SessionCookie.Name);
            return TypedResults.NoContent();
        });

        return group;
    }
}