using Knoks.Api.Controllers.Base;
using Knoks.Api.Entities;
using Knoks.Api.Logic.Interfaces;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using System;
using static Knoks.Api.Authentication.IdentityConsts;

namespace Knoks.Api.Filters
{
    public class ApiIdentifierActionFilter : Attribute, IActionFilter
    {
        private readonly ILogger _logger;
        private readonly IApiConsumerManager _apiConsumerManager;

        public ApiIdentifierActionFilter(ILogger<ApiIdentifierActionFilter> logger, IApiConsumerManager apiConsumerManager)
        {
            _logger = logger;
            _apiConsumerManager = apiConsumerManager;
        }

        public void OnActionExecuted(ActionExecutedContext context)
        {
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            var apiIdentifier = Convert.ToString(context.RouteData.Values["apiIdentifier"]);

            if (string.IsNullOrEmpty(apiIdentifier))
            {
                var apiIdentifierClaim = context.HttpContext.User.FindFirst(ApiIdentifierClaim);
                if (apiIdentifierClaim == null)
                    return;

                apiIdentifier = apiIdentifierClaim.Value;
            }

            if (!_apiConsumerManager.ApiConsumers.TryGetValue(apiIdentifier, out ApiConsumer apiConsumer))
                throw new ApiResponseException(ApiErrorType.InvalidApiIdentifier, $"Invalid api identifier '{apiIdentifier}'.");

            if (!apiConsumer.IsEnabled)
                throw new ApiResponseException(ApiErrorType.ApiConsumerIsDisabled, $"Api consumer #{apiConsumer.Id} is disabled.");

            context.GetApiBaseController().ContextApiConsumer = apiConsumer;
        }
    }
}
