using adas_core.Application.Services.Interfaces;
using Microsoft.Extensions.Logging;

namespace adas_core.Application.Services.Caching
{
    /// <summary>
    /// Servicio que ejecuta acciones dentro de una sección crítica controlada por lock.
    /// CacheService lo usará para evitar condiciones de carrera en GetOrSet.
    /// Funciona igual para locks locales o distribuidos.
    /// </summary>
    public class LockManagerService(
        ILogger<LockManagerService> logger,
        ILockProvider provider)
    {
        /// <summary>
        /// Ejecuta una función que devuelve un valor bajo un lock por clave.
        /// </summary>
        public async Task<T> WithLockAsync<T>(
            string key,
            TimeSpan timeout,
            Func<Task<T>> action,
            CancellationToken cancellationToken = default)
        {
            logger.LogDebug(
                "LockManager — intentando adquirir lock para key={Key} timeout={TimeoutMs}ms",
                key, timeout.TotalMilliseconds);

            var acquired = false;

            try
            {
                acquired = await provider.AcquireAsync(key, timeout).ConfigureAwait(false);

                if (!acquired)
                {
                    logger.LogWarning(
                        "LockManager — timeout al adquirir lock para key={Key} tras {TimeoutMs}ms",
                        key, timeout.TotalMilliseconds);
                    throw new TimeoutException($"No se pudo adquirir el lock para '{key}'");
                }

                logger.LogDebug(
                    "LockManager — lock adquirido correctamente para key={Key}",
                    key);

                return await action().ConfigureAwait(false);
            }
            finally
            {
                if (acquired)
                {
                    await SafeReleaseAsync(key);
                }
            }
        }

        /// <summary>
        /// Version Task (sin valor).
        /// </summary>
        public Task WithLockAsync(
            string key,
            TimeSpan timeout,
            Func<Task> action,
            CancellationToken cancellationToken = default)
        {
            return WithLockAsync<object?>(
                key,
                timeout,
                async () =>
                {
                    await action();
                    return null;
                },
                cancellationToken);
        }

        /// <summary>
        /// Libera el lock y registra posibles errores sin interrumpir el flujo.
        /// </summary>
        private async Task SafeReleaseAsync(string key)
        {
            try
            {
                await provider.ReleaseAsync(key).ConfigureAwait(false);
                logger.LogDebug("LockManager — key={Key} lock deleted ", key);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "LockManager —  key={Key} error deleting lock", key);
            }
        }
    }
}