using CONTROLLER.Models;
using Microsoft.AspNetCore.Http;
using System.Linq;
using System.Threading.Tasks;

namespace CONTROLLER.Middleware
{
    public class RequestTrackingMiddleware
    {
        private readonly RequestDelegate _next;

        public RequestTrackingMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            var trackingContext = new RequestTrackingContext();

            var caller = context.Request.Headers["Caller"].FirstOrDefault();
            if (!string.IsNullOrWhiteSpace(caller))
            {
                trackingContext.Caller = caller;
            }

            var deviceCode = context.Request.Headers["DeviceCode"].FirstOrDefault();
            if (!string.IsNullOrWhiteSpace(deviceCode))
            {
                trackingContext.DeviceCode = deviceCode;
            }

            var deviceName = context.Request.Headers["DeviceName"].FirstOrDefault();
            if (!string.IsNullOrWhiteSpace(deviceName))
            {
                trackingContext.DeviceName = deviceName;
            }

            context.Items["RequestTrackingContext"] = trackingContext;
            await _next(context);
        }
    }
}
