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

namespace Web.Api.Endpoints.Forum.Post;

internal sealed class Create : IEndpoint
{
    public sealed class Request
    {
        public int BoardID { get; set; }
        public string? BoardCode { get; set; }
        public int? BoardPrefixID { get; set; }
        public string Subject { get; set; } = "";
        public string Content { get; set; } = "";
        public bool IsSecret { get; set; }
        public bool IsNotice { get; set; }
        public bool IsSpeaker { get; set; }
        public List<string>? Tags { get; set; }
        public List<string>? Medias { get; set; }
    }

    public void MapEndpoint(IEndpointRouteBuilder app)
    {
        app.MapPost("api/forum/posts", 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.Post.Create.Command(
                memberID.Value,
                request.BoardID,
                request.BoardPrefixID,
                request.Subject,
                request.Content,
                request.IsSecret,
                request.IsNotice,
                request.IsSpeaker,
                request.Tags,
                images.Count > 0 ? images : null,
                request.Medias,
                files.Count > 0 ? files : null
            );

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

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