using System.Net;

namespace ApiBloqueioIp.Services;

public class BloquearIPMiddleware
{
    private readonly RequestDelegate _next;
    private readonly IBloquearIPService _bloquearIpService;

    public BloquearIPMiddleware(RequestDelegate next, IBloquearIPService bloquearIpService)
    {
        _next = next;
        _bloquearIpService = bloquearIpService;
    }

    public async Task Invoke(HttpContext context)
    {
        var remoteIp = context.Connection.RemoteIpAddress;

        var estaBloqueado = _bloquearIpService.EstaBloqueado(remoteIp!);

        if (estaBloqueado)
        {
            context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
            return;
        }

        await _next.Invoke(context);
    }
}
