using Application.Abstractions.Messaging;
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 Update : IEndpoint
{
    public sealed class Request
    {
        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.MapPut("api/forum/comments/{id}", async (
            int id,
            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.Update.Command(
                id,
                memberID.Value,
                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(
                () => ApiResponse.Ok(),
                CustomResults.Problem
            );
        })
        .WithTags("Forum")
        .RequireAuthorization()
        .DisableAntiforgery();
    }
}
