using System.Net;
using System.Text;

namespace API.Middlewares;

public class BodyCheckMiddleware(RequestDelegate next)
{
    private readonly RequestDelegate _next = next;

    public async Task InvokeAsync(HttpContext context)
    {
        // Only check the body for POST and PUT requests
        if (context.Request.Method == HttpMethods.Post || context.Request.Method == HttpMethods.Put)
        {
            // Enable buffering so we can read the stream without issues downstream
            context.Request.EnableBuffering();

            var buffer = new byte[Convert.ToInt32(context.Request.ContentLength)];
            await context.Request.Body.ReadAsync(buffer, 0, buffer.Length);
            var requestBody = Encoding.UTF8.GetString(buffer);
            context.Request.Body.Seek(0, SeekOrigin.Begin); // Reset the stream for next middleware

            // Check if the body is empty
            if (string.IsNullOrEmpty(requestBody))
            {
                context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                await context.Response.WriteAsync("Request body cannot be empty.");
                return;
            }
        }

        await _next(context);
    }
}