namespace AAIntegration.SimmonsBank.API.Services;

using Microsoft.Extensions.Caching.Memory;

public interface ICacheService
{
    int GetClientIdFromApiKey(string apiKey);
}

public class CacheService : ICacheService
{
    private readonly IMemoryCache _memoryCache;
    private readonly IUserService _userService;
    private readonly ILogger<ICacheService> _logger;

    public CacheService(IMemoryCache memoryCache, IUserService userService, ILogger<ICacheService> logger)
    {
        _memoryCache = memoryCache;
        _userService = userService;
        _logger = logger;
    }

    public int GetClientIdFromApiKey(string apiKey)
    {
        if (!_memoryCache.TryGetValue<Dictionary<string, int>>($"Authentication_ApiKeys", out var internalKeys))
        {
            _logger.LogInformation($"Could not find API key '{apiKey}' in cache.");

            internalKeys = _userService.GetAllApiKeys();

            _logger.LogInformation("Updated cache with new key list.");
            PrintInternalKeys(internalKeys);

            _memoryCache.Set($"Authentication_ApiKeys", internalKeys);
        }

        if (!internalKeys.TryGetValue(apiKey, out var clientId))
        {
            _logger.LogInformation("Could not find API key. Returning -1.");
            return -1;
        }

        return clientId;
    }
    
    // helpers

    private void PrintInternalKeys(Dictionary<string, int> keys)
    {
        string msg = "API Keys (dev only - needs to be moved to dev only)";
        foreach (var item in keys)
            msg += $"\n\t{item.Value} : {item.Key}";

        _logger.LogInformation(msg);
    }

    /*public void InvalidateApiKey(string apiKey)
    {
        if (_memoryCache.TryGetValue<Dictionary<string, Guid>>("Authentication_ApiKeys", out var internalKeys))
        {
            if (internalKeys.ContainsKey(apiKey))
            {
                internalKeys.Remove(apiKey);
                _memoryCache.Set("Authentication_ApiKeys", internalKeys);
            }
        }

        _userService.InvalidateApiKey(apiKey);
    }*/
}
