using MediatR;
using Web.Api.Common;
using Web.Api.Extensions;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;

namespace Web.Api.Endpoints.Forum.Comment;

internal sealed class Create : IEndpoint
{
    public sealed class Request
    {
        public int PostID { get; set; }
        public int? ParentID { get; set; }
        public string? Mention { get; set; }
        public string Content { get; set; } = "";
        public bool IsSecret { get; set; }
        public List<string>? Medias { get; set; }
    }

    public void MapEndpoint(IEndpointRouteBuilder app)
    {
        app.MapPost("api/forum/comments", async (
            ClaimsPrincipal user,
            [FromForm] Request request,
            HttpRequest httpRequest,
            ISender sender,
            CancellationToken ct
        ) => {
            var memberID = user.GetMemberID();

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

            var images = httpRequest.Form.Files.GetFiles("images").ToList();
            var files = httpRequest.Form.Files.GetFiles("files").ToList();

            var command = new Application.Features.Api.Forum.Comment.Create.Command(
                memberID.Value,
                request.PostID,
                request.ParentID,
                request.Mention,
                request.Content,
                request.IsSecret,
                images.Count > 0 ? images : null,
                request.Medias,
                files.Count > 0 ? files : null
            );

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

            return result.Match(
                commentID => ApiResponse.Created(new { id = commentID }),
                CustomResults.Problem
            );
        })
        .WithTags("Forum")
        .RequireAuthorization()
        .DisableAntiforgery();
    }
}
