using System.Security.Claims;
using Application.Common;
using MediatR;
using Web.Api.Common;
using Web.Api.Extensions;

namespace Web.Api.Endpoints.MyPage;

internal sealed class GetExpLogs : IEndpoint
{
    public void MapEndpoint(IEndpointRouteBuilder app)
    {
        app.MapGet("api/mypage/exp-logs", async (
            string? type,
            int? page,
            int? perPage,
            ClaimsPrincipal user,
            ISender sender,
            CancellationToken ct
        ) => {
            var memberID = user.GetMemberID();

            if (memberID is null)
            {
                return ApiResponse.Fail(StatusCodes.Status401Unauthorized, "Invalid token");
            }

            var searchType = type ?? SearchDateType.Today;
            if (!SearchDateType.ValidTypes.Contains(searchType))
            {
                return ApiResponse.Fail(StatusCodes.Status400BadRequest, "Invalid type");
            }

            var query = new Application.Features.Api.MyPage.GetExpLogs.Query(
                memberID.Value,
                searchType,
                page ?? 1,
                perPage ?? 20
            );

            var result = await sender.Send(query, ct);

            return result.Match(
                data => ApiResponse.Ok(data),
                CustomResults.Problem
            );
        })
        .WithTags("MyPage")
        .RequireAuthorization();
    }
}