using System.Net;

namespace Electricity.Api.Middlewares;

internal sealed class IpFilterMiddleware(RequestDelegate next, IConfiguration configuration)
{
    private readonly RequestDelegate _next = next;
    private readonly string AllowedHost = configuration["AllowedRequestHost"]
        ?? throw new NullReferenceException($"Configuration value AllowedRequestHost is not available");

    public async Task InvokeAsync(HttpContext context)
    {
        var selfIpAddress = (await Dns.GetHostEntryAsync(AllowedHost)).AddressList.FirstOrDefault()?.MapToIPv4().ToString();
        if (selfIpAddress == null ||
            !context.Request.Headers.TryGetValue("X-Real-IP", out var realIpHeaderValue) ||
            selfIpAddress != realIpHeaderValue.ToString())
        {
            context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
            return;
        }

        // Call the next delegate/middleware in the pipeline.
        await _next(context);
    }
}