using System;
using System.IO;
using FluentAssertions;
using Newtonsoft.Json;
using Xunit;
using ZB.MOM.WW.LmxProxy.Host.Security;

namespace ZB.MOM.WW.LmxProxy.Host.Tests.Security
{
    public class ApiKeyServiceTests : IDisposable
    {
        private readonly string _tempDir;

        public ApiKeyServiceTests()
        {
            _tempDir = Path.Combine(Path.GetTempPath(), "lmxproxy-test-" + Guid.NewGuid().ToString("N").Substring(0, 8));
            Directory.CreateDirectory(_tempDir);
        }

        public void Dispose()
        {
            if (Directory.Exists(_tempDir))
                Directory.Delete(_tempDir, true);
        }

        private string CreateKeyFile(params ApiKey[] keys)
        {
            var path = Path.Combine(_tempDir, "apikeys.json");
            var config = new ApiKeyConfiguration { ApiKeys = new System.Collections.Generic.List<ApiKey>(keys) };
            File.WriteAllText(path, JsonConvert.SerializeObject(config, Formatting.Indented));
            return path;
        }

        [Fact]
        public void AutoGeneratesDefaultFile_WhenMissing()
        {
            var path = Path.Combine(_tempDir, "missing.json");
            using (var svc = new ApiKeyService(path))
            {
                File.Exists(path).Should().BeTrue();
                svc.KeyCount.Should().Be(2);
            }
        }

        [Fact]
        public void ValidateApiKey_ReturnsKey_WhenValid()
        {
            var path = CreateKeyFile(new ApiKey { Key = "test-key", Role = ApiKeyRole.ReadWrite, Enabled = true });
            using (var svc = new ApiKeyService(path))
            {
                var key = svc.ValidateApiKey("test-key");
                key.Should().NotBeNull();
                key!.Role.Should().Be(ApiKeyRole.ReadWrite);
            }
        }

        [Fact]
        public void ValidateApiKey_ReturnsNull_WhenInvalid()
        {
            var path = CreateKeyFile(new ApiKey { Key = "test-key", Role = ApiKeyRole.ReadWrite, Enabled = true });
            using (var svc = new ApiKeyService(path))
            {
                svc.ValidateApiKey("wrong-key").Should().BeNull();
            }
        }

        [Fact]
        public void ValidateApiKey_ReturnsNull_WhenDisabled()
        {
            var path = CreateKeyFile(new ApiKey { Key = "test-key", Role = ApiKeyRole.ReadWrite, Enabled = false });
            using (var svc = new ApiKeyService(path))
            {
                svc.ValidateApiKey("test-key").Should().BeNull();
            }
        }

        [Fact]
        public void HasRole_ReadWrite_CanRead()
        {
            var path = CreateKeyFile(new ApiKey { Key = "rw", Role = ApiKeyRole.ReadWrite, Enabled = true });
            using (var svc = new ApiKeyService(path))
            {
                svc.HasRole("rw", ApiKeyRole.ReadOnly).Should().BeTrue();
            }
        }

        [Fact]
        public void HasRole_ReadOnly_CannotWrite()
        {
            var path = CreateKeyFile(new ApiKey { Key = "ro", Role = ApiKeyRole.ReadOnly, Enabled = true });
            using (var svc = new ApiKeyService(path))
            {
                svc.HasRole("ro", ApiKeyRole.ReadWrite).Should().BeFalse();
            }
        }

        [Fact]
        public void HasRole_ReadWrite_CanWrite()
        {
            var path = CreateKeyFile(new ApiKey { Key = "rw", Role = ApiKeyRole.ReadWrite, Enabled = true });
            using (var svc = new ApiKeyService(path))
            {
                svc.HasRole("rw", ApiKeyRole.ReadWrite).Should().BeTrue();
            }
        }

        [Fact]
        public void ValidateApiKey_EmptyString_ReturnsNull()
        {
            var path = CreateKeyFile(new ApiKey { Key = "test", Enabled = true });
            using (var svc = new ApiKeyService(path))
            {
                svc.ValidateApiKey("").Should().BeNull();
                svc.ValidateApiKey(null!).Should().BeNull();
            }
        }
    }
}
