using System.Reflection;
using adas_core.Application.Services.Caching;
using adas_core.Domain.Models.AppSettings;
using Microsoft.Extensions.Logging;
using Moq;
using Newtonsoft.Json;
using StackExchange.Redis;
using Options = Microsoft.Extensions.Options.Options;

namespace adas_core.Test.Services;

[TestFixture]
public class RedisServiceTest
{
    private record TestModel(string Name);

    private Mock<IDatabase> _mockDb = null!;
    private LockManagerService _lockMgr = null!;

    /// <summary>
    /// Initializes test dependencies before each test execution by creating a mock <see cref="IDatabase"/> instance and instantiating the <see cref="LockManagerService"/> with a mocked logger and an in-memory lock provider.
    /// </summary>
    [SetUp]
        public void SetUp()
        {
            _mockDb = new Mock<IDatabase>();
            _lockMgr = new LockManagerService(
                new Mock<ILogger<LockManagerService>>().Object,
                new InMemoryLockProvider());
        }

    /// <summary>
    /// Creates a configured instance of <see cref="RedisService"/> for testing, allowing
    /// optional customization of cache settings and the simulated availability of the Redis backend.
    /// </summary>
    /// <param name="settings">Optional cache settings to apply; when <c>null</c>, a new default <see cref="CacheSettings"/> instance is used.</param>
    /// <param name="redisAvailable">Flag indicating whether the Redis service should be marked as available; defaults to <c>true</c>.</param>
    /// <returns>A <see cref="RedisService"/> instance with the database and availability state initialized for testing.</returns>
    private RedisService CreateSut(CacheSettings? settings = null, bool redisAvailable = true)
        {
            var sut = new RedisService(
                Options.Create(settings ?? new CacheSettings()),
                new Mock<ILogger<RedisService>>().Object,
                _lockMgr);
    
            SetField(sut, "_database", _mockDb.Object);
            SetField(sut, "_isRedisAvailable", redisAvailable);
    
            return sut;
        }

    /// <summary>
    /// Sets the value of a non-public instance field on a <see cref="RedisService"/> object using reflection.
    /// </summary>
    /// <param name="target">The <see cref="RedisService"/> instance whose field will be set.</param>
    /// <param name="name">The name of the non-public instance field to assign.</param>
    /// <param name="value">The value to assign to the field. Can be null.</param>
    private static void SetField(object target, string name, object? value)
            => typeof(RedisService)
                .GetField(name, BindingFlags.NonPublic | BindingFlags.Instance)!
                .SetValue(target, value);

    /// <summary>
    /// Configures the mock database to return a successful result (<c>true</c>) for any invocation of <c>StringSetAsync</c>, regardless of the supplied key, value, expiry, overwrite flag, condition, or command flags.
    /// </summary>
    private void SetupStringSetAsync()
            => _mockDb
                .Setup(db => db.StringSetAsync(
                    It.IsAny<RedisKey>(), It.IsAny<RedisValue>(), It.IsAny<TimeSpan?>(),
                    It.IsAny<bool>(), It.IsAny<When>(), It.IsAny<CommandFlags>()))
                .ReturnsAsync(true);

    /// <summary>
    /// Configures the mock Redis database to handle <c>KeyExpire</c> calls by returning <c>true</c> for any combination of key, expiration, condition, and command flag arguments.
    /// </summary>
    private void SetupKeyExpire()
            => _mockDb
                .Setup(db => db.KeyExpire(
                    It.IsAny<RedisKey>(), It.IsAny<TimeSpan?>(),
                    It.IsAny<ExpireWhen>(), It.IsAny<CommandFlags>()))
                .Returns(true);

    #region TC-38
    /// <summary>
    /// Verifies that <c>GetOrSetObjectAsync</c> invokes the supplied factory when Redis is unavailable, returning the factory's result without attempting any Redis read or write operations.
    /// </summary>
    [Test]
        public async Task GetOrSetObjectAsync_ExecutesFactory_WhenRedisUnavailable()
        {
            var sut = CreateSut(redisAvailable: false);
            var factoryInvoked = false;
    
            var result = await sut.GetOrSetObjectAsync<string>(
                "patients:latestObs:abc",
                () => { factoryInvoked = true; return Task.FromResult("result"); });
    
            Assert.That(factoryInvoked, Is.True);
            Assert.That(result, Is.EqualTo("result"));
            _mockDb.Verify(db => db.StringGetAsync(It.IsAny<RedisKey>(), It.IsAny<CommandFlags>()), Times.Never);
            _mockDb.Verify(db => db.StringSetAsync(It.IsAny<RedisKey>(), It.IsAny<RedisValue>(), It.IsAny<TimeSpan?>(), It.IsAny<bool>(), It.IsAny<When>(), It.IsAny<CommandFlags>()), Times.Never);
        }
    #endregion

    #region TC-39
    /// <summary>
    /// Verifies that <c>GetOrSetObjectAsync</c> returns the cached object deserialized from Redis
    /// when a value is present in the cache, without invoking the factory delegate and without
    /// attempting to write back to Redis.
    /// </summary>
    [Test]
        public async Task GetOrSetObjectAsync_ReturnsCachedObject_WhenRedisHit()
        {
            var cached = new TestModel("cached");
    
            _mockDb.Setup(db => db.StringGetAsync(It.IsAny<RedisKey>(), It.IsAny<CommandFlags>()))
                   .ReturnsAsync((RedisValue)JsonConvert.SerializeObject(cached));
            SetupKeyExpire();
    
            var sut = CreateSut();
            var factoryInvoked = false;
    
            var result = await sut.GetOrSetObjectAsync<TestModel>(
                "patients:latestObs:abc",
                () => { factoryInvoked = true; return Task.FromResult(new TestModel("fresh")); });
    
            Assert.That(factoryInvoked, Is.False);
            Assert.That(result?.Name, Is.EqualTo("cached"));
            _mockDb.Verify(db => db.StringSetAsync(It.IsAny<RedisKey>(), It.IsAny<RedisValue>(), It.IsAny<TimeSpan?>(), It.IsAny<bool>(), It.IsAny<When>(), It.IsAny<CommandFlags>()), Times.Never);
        }
    #endregion

    #region TC-40
    /// <summary>
    /// Verifies that <c>GetObjectAsync</c> calls the underlying Redis <c>KeyExpire</c> command with the configured TTL
    /// when the <c>updateExpiration</c> flag is set to <c>true</c>, ensuring cache entries are refreshed upon a successful hit.
    /// </summary>
    [Test]
        public async Task GetObjectAsync_CallsKeyExpire_WhenUpdateExpirationIsTrue()
        {
            var settings = new CacheSettings
            {
                Redis = new RedisSettings { Ttl = new TtlSettings { PatientsSeconds = 300 } }
            };
    
            _mockDb.Setup(db => db.StringGetAsync(It.IsAny<RedisKey>(), It.IsAny<CommandFlags>()))
                   .ReturnsAsync((RedisValue)JsonConvert.SerializeObject(new TestModel("hit")));
            SetupKeyExpire();
    
            var sut = CreateSut(settings);
    
            await sut.GetObjectAsync<TestModel>("patients:latestObs:abc", updateExpiration: true);
    
            _mockDb.Verify(
                db => db.KeyExpire(
                    It.IsAny<RedisKey>(),
                    It.Is<TimeSpan?>(t => t == TimeSpan.FromSeconds(300)),
                    It.IsAny<ExpireWhen>(),
                    It.IsAny<CommandFlags>()),
                Times.Once);
        }

    /// <summary>
    /// Verifies that <c>GetObjectAsync</c> does not invoke the Redis key expiration command
    /// when the caller explicitly requests that the existing expiration be left unchanged.
    /// </summary>
    [Test]
        public async Task GetObjectAsync_DoesNotCallKeyExpire_WhenUpdateExpirationIsFalse()
        {
            _mockDb.Setup(db => db.StringGetAsync(It.IsAny<RedisKey>(), It.IsAny<CommandFlags>()))
                   .ReturnsAsync((RedisValue)JsonConvert.SerializeObject(new TestModel("hit")));
    
            var sut = CreateSut();
    
            await sut.GetObjectAsync<TestModel>("patients:latestObs:abc", updateExpiration: false);
    
            _mockDb.Verify(
                db => db.KeyExpire(It.IsAny<RedisKey>(), It.IsAny<TimeSpan?>(), It.IsAny<ExpireWhen>(), It.IsAny<CommandFlags>()),
                Times.Never);
        }
    #endregion

    #region TC-41
    /// <summary>
    /// Verifies that <c>GetOrSetObjectAsync</c> invokes the supplied factory and persists the resulting object
    /// to Redis with the configured TTL when the cache lookup returns a miss (i.e., the stored value is null).
    /// Ensures the factory delegate is executed, the deserialized value matches the factory output, and the
    /// object is written to cache with the expected expiration.
    /// </summary>
    [Test]
        public async Task GetOrSetObjectAsync_InvokesFactoryAndPersists_WhenCacheMiss()
        {
            var settings = new CacheSettings
            {
                Redis = new RedisSettings { Ttl = new TtlSettings { PatientsSeconds = 300, PatientObservationsSeconds = 300} }
            };
    
            _mockDb.Setup(db => db.StringGetAsync(It.IsAny<RedisKey>(), It.IsAny<CommandFlags>()))
                   .ReturnsAsync(RedisValue.Null);
            SetupStringSetAsync();
    
            var sut = CreateSut(settings);
            var expected = new TestModel("fresh");
            var factoryInvoked = false;
    
            var result = await sut.GetOrSetObjectAsync<TestModel>(
                "patients:latestObs:abc",
                () => { factoryInvoked = true; return Task.FromResult(expected); });
    
            var expectedJson = JsonConvert.SerializeObject(expected);
    
            Assert.That(factoryInvoked, Is.True);
            Assert.That(result?.Name, Is.EqualTo("fresh"));
            _mockDb.Verify(
                db => db.StringSetAsync(
                    It.IsAny<RedisKey>(),
                    It.IsAny<RedisValue>(),
                    It.Is<TimeSpan?>(t => t == TimeSpan.FromSeconds(300)),
                    It.IsAny<bool>(),
                    It.IsAny<When>(),
                    It.IsAny<CommandFlags>()),
                Times.Once);
            It.Is<RedisValue>(v => v.Equals(expectedJson));
        }
    #endregion

    #region TC-42
    /// <summary>
    /// Verifies that when the cache lookup returns no value and the factory delegate produces <c>null</c>,
    /// the method returns <c>null</c> and does not persist any value to the underlying cache store.
    /// </summary>
    [Test]
        public async Task GetOrSetObjectAsync_DoesNotPersist_WhenFactoryReturnsNull()
        {
            _mockDb.Setup(db => db.StringGetAsync(It.IsAny<RedisKey>(), It.IsAny<CommandFlags>()))
                   .ReturnsAsync(RedisValue.Null);
    
            var sut = CreateSut();
    
            var result = await sut.GetOrSetObjectAsync<TestModel?>(
                "patients:latestObs:abc",
                () => Task.FromResult<TestModel?>(null));
    
            Assert.That(result, Is.Null);
            _mockDb.Verify(
                db => db.StringSetAsync(It.IsAny<RedisKey>(), It.IsAny<RedisValue>(), It.IsAny<TimeSpan?>(), It.IsAny<bool>(), It.IsAny<When>(), It.IsAny<CommandFlags>()),
                Times.Never);
        }
    #endregion

    #region TC-43
    /// <summary>
    /// Verifies that <c>GetObjectAsync</c> successfully retrieves and deserializes the stored object while skipping the
    /// key-expiration refresh when <c>updateExpiration</c> is set to <c>false</c>, ensuring <c>KeyExpire</c> is never invoked.
    /// </summary>
    [Test]
        public async Task GetObjectAsync_ReturnsObject_AndSkipsKeyExpire_WhenUpdateExpirationFalse()
        {
            var expected = new TestModel("data");
    
            _mockDb.Setup(db => db.StringGetAsync(It.IsAny<RedisKey>(), It.IsAny<CommandFlags>()))
                   .ReturnsAsync((RedisValue)JsonConvert.SerializeObject(expected));
    
            var sut = CreateSut();
    
            var result = await sut.GetObjectAsync<TestModel>("patients:latestObs:abc", updateExpiration: false);
    
            Assert.That(result?.Name, Is.EqualTo("data"));
            _mockDb.Verify(
                db => db.KeyExpire(It.IsAny<RedisKey>(), It.IsAny<TimeSpan?>(), It.IsAny<ExpireWhen>(), It.IsAny<CommandFlags>()),
                Times.Never);
        }
    #endregion

    #region TC-44
    /// <summary>
    /// Verifies that <c>SetObjectAsync</c> serializes the supplied object to JSON and persists it in Redis
    /// with the entity-specific TTL (600 seconds) configured for the "Patients" entity in <see cref="CacheSettings"/>.
    /// </summary>
    [Test]
        public async Task SetObjectAsync_SerializesToJson_AndPersistsWithEntityTtl()
        {
            var settings = new CacheSettings
            {
                Redis = new RedisSettings { Ttl = new TtlSettings { PatientsSeconds = 600 } }
            };
    
            SetupStringSetAsync();
    
            var sut = CreateSut(settings);
            var obj = new TestModel("save-me");
            var expectedJson = JsonConvert.SerializeObject(obj);
    
            await sut.SetObjectAsync("patients:latestObs:abc", obj, null, true);
            _mockDb.Verify(
                db => db.StringSetAsync(
                    It.IsAny<RedisKey>(),
                    It.IsAny<RedisValue>(),
                    It.Is<TimeSpan?>(t => t == TimeSpan.FromSeconds(600)),
                    It.IsAny<bool>(),
                    It.IsAny<When>(),
                    It.IsAny<CommandFlags>()),
                Times.Once);
            It.Is<RedisValue>(v => v.Equals(expectedJson));
    
        }
    #endregion
}
