using System.Security.Cryptography;
using System.Text;
using Microsoft.Extensions.Caching.Memory;
using Nalu.Web.Models;

namespace Nalu.Web.Services;

public class CacheService
{
    private readonly IMemoryCache _cache;
    private readonly IConfiguration _config;

    public CacheService(IMemoryCache cache, IConfiguration config)
    {
        _cache = cache;
        _config = config;
    }

    public bool TryGet(string validatorId, ExtractionRequest request, out ExtractionResponse? response)
    {
        var key = ComputeKey(validatorId, request);
        return _cache.TryGetValue(key, out response);
    }

    public void Set(string validatorId, ExtractionRequest request, ExtractionResponse response)
    {
        var ttl = _config.GetValue<int>("Cache:DefaultTtlMinutes", 60);
        var key = ComputeKey(validatorId, request);
        _cache.Set(key, response, TimeSpan.FromMinutes(ttl));
    }

    private static string ComputeKey(string validatorId, ExtractionRequest request)
    {
        var raw = $"{validatorId}|{request.AgentInput}|{request.UserInput}|{request.Language}";
        var hash = SHA256.HashData(Encoding.UTF8.GetBytes(raw));
        return Convert.ToHexString(hash);
    }
}
