using Grpc.Core;
using Microsoft.Extensions.Logging.Abstractions;
using ZB.MOM.WW.MxGateway.Contracts.Proto.Galaxy;
using ZB.MOM.WW.MxGateway.Server.Dashboard;
using ZB.MOM.WW.MxGateway.Server.Galaxy;
using ZB.MOM.WW.MxGateway.Server.Grpc;
using ZB.MOM.WW.MxGateway.Server.Security.Authorization;
using ZB.MOM.WW.MxGateway.Tests.TestSupport;

namespace ZB.MOM.WW.MxGateway.Tests.Gateway.Grpc;

public sealed class GalaxyRepositoryGrpcServiceTests
{
    [Fact]
    public async Task DiscoverHierarchy_ReturnsRequestedPageAndTotals()
    {
        GalaxyRepositoryGrpcService service = CreateService(CreateEntry(CreateObjects(3)));

        DiscoverHierarchyReply reply = await service.DiscoverHierarchy(
            new DiscoverHierarchyRequest
            {
                PageSize = 2,
            },
            new TestServerCallContext());

        Assert.Equal(2, reply.Objects.Count);
        Assert.Equal("Object_001", reply.Objects[0].TagName);
        Assert.Equal("Object_002", reply.Objects[1].TagName);
        Assert.StartsWith("7:", reply.NextPageToken, StringComparison.Ordinal);
        Assert.EndsWith(":2", reply.NextPageToken, StringComparison.Ordinal);
        Assert.Equal(3, reply.TotalObjectCount);
    }

    [Fact]
    public async Task DiscoverHierarchy_WithNextPageToken_ReturnsRemainingObjects()
    {
        GalaxyRepositoryGrpcService service = CreateService(CreateEntry(CreateObjects(3)));
        DiscoverHierarchyReply firstPage = await service.DiscoverHierarchy(
            new DiscoverHierarchyRequest
            {
                PageSize = 2,
            },
            new TestServerCallContext());

        DiscoverHierarchyReply reply = await service.DiscoverHierarchy(
            new DiscoverHierarchyRequest
            {
                PageSize = 2,
                PageToken = firstPage.NextPageToken,
            },
            new TestServerCallContext());

        GalaxyObject item = Assert.Single(reply.Objects);
        Assert.Equal("Object_003", item.TagName);
        Assert.Equal("", reply.NextPageToken);
        Assert.Equal(3, reply.TotalObjectCount);
    }

    [Theory]
    [InlineData("-1", 1)]
    [InlineData("not-an-offset", 1)]
    [InlineData("7:4", 1)]
    [InlineData("6:2", 1)]
    [InlineData("", -1)]
    public async Task DiscoverHierarchy_WithInvalidPagingArguments_ReturnsInvalidArgument(
        string pageToken,
        int pageSize)
    {
        GalaxyRepositoryGrpcService service = CreateService(CreateEntry(CreateObjects(3)));

        RpcException exception = await Assert.ThrowsAsync<RpcException>(
            async () => await service.DiscoverHierarchy(
                new DiscoverHierarchyRequest
                {
                    PageSize = pageSize,
                    PageToken = pageToken,
                },
                new TestServerCallContext()));

        Assert.Equal(StatusCode.InvalidArgument, exception.StatusCode);
    }

    [Fact]
    public async Task DiscoverHierarchy_WithSubtreeRootAndDepth_FiltersDescendants()
    {
        GalaxyRepositoryGrpcService service = CreateService(CreateEntry(CreateFilterObjects()));

        DiscoverHierarchyReply reply = await service.DiscoverHierarchy(
            new DiscoverHierarchyRequest
            {
                RootContainedPath = "Area1/Line3",
                MaxDepth = 1,
                PageSize = 10,
            },
            new TestServerCallContext());

        Assert.Equal(["Line3", "Pump_001", "Valve_001"], reply.Objects.Select(obj => obj.TagName));
        Assert.Equal(3, reply.TotalObjectCount);
    }

    [Fact]
    public async Task DiscoverHierarchy_WithServerSideFilters_AppliesAllFiltersAndOmitsAttributes()
    {
        GalaxyRepositoryGrpcService service = CreateService(CreateEntry(CreateFilterObjects()));

        DiscoverHierarchyReply reply = await service.DiscoverHierarchy(
            new DiscoverHierarchyRequest
            {
                RootTagName = "Area1",
                TagNameGlob = "Pump_*",
                AlarmBearingOnly = true,
                HistorizedOnly = true,
                IncludeAttributes = false,
                PageSize = 10,
                CategoryIds = { 10 },
                TemplateChainContains = { "Pump" },
            },
            new TestServerCallContext());

        GalaxyObject obj = Assert.Single(reply.Objects);
        Assert.Equal("Pump_001", obj.TagName);
        Assert.Empty(obj.Attributes);
        Assert.Equal(1, reply.TotalObjectCount);
    }

    [Fact]
    public async Task DiscoverHierarchy_WithFilteredPaging_ReturnsPostFilterTotal()
    {
        GalaxyRepositoryGrpcService service = CreateService(CreateEntry(CreateFilterObjects()));

        DiscoverHierarchyReply first = await service.DiscoverHierarchy(
            new DiscoverHierarchyRequest
            {
                RootGobjectId = 1,
                PageSize = 1,
                CategoryIds = { 10 },
            },
            new TestServerCallContext());

        DiscoverHierarchyReply second = await service.DiscoverHierarchy(
            new DiscoverHierarchyRequest
            {
                RootGobjectId = 1,
                PageSize = 1,
                PageToken = first.NextPageToken,
                CategoryIds = { 10 },
            },
            new TestServerCallContext());

        GalaxyObject firstObject = Assert.Single(first.Objects);
        GalaxyObject secondObject = Assert.Single(second.Objects);
        Assert.Equal(2, first.TotalObjectCount);
        Assert.Equal(2, second.TotalObjectCount);
        Assert.NotEqual(firstObject.TagName, secondObject.TagName);
    }

    [Fact]
    public async Task DiscoverHierarchy_WithMismatchedFilterToken_ReturnsInvalidArgument()
    {
        GalaxyRepositoryGrpcService service = CreateService(CreateEntry(CreateFilterObjects()));
        DiscoverHierarchyReply first = await service.DiscoverHierarchy(
            new DiscoverHierarchyRequest
            {
                PageSize = 1,
                CategoryIds = { 10 },
            },
            new TestServerCallContext());

        RpcException exception = await Assert.ThrowsAsync<RpcException>(
            async () => await service.DiscoverHierarchy(
                new DiscoverHierarchyRequest
                {
                    PageSize = 1,
                    PageToken = first.NextPageToken,
                    CategoryIds = { 11 },
                },
                new TestServerCallContext()));

        Assert.Equal(StatusCode.InvalidArgument, exception.StatusCode);
        Assert.Contains("filters", exception.Status.Detail, StringComparison.OrdinalIgnoreCase);
    }

    [Fact]
    public async Task DiscoverHierarchy_WithMissingRoot_ReturnsNotFound()
    {
        GalaxyRepositoryGrpcService service = CreateService(CreateEntry(CreateFilterObjects()));

        RpcException exception = await Assert.ThrowsAsync<RpcException>(
            async () => await service.DiscoverHierarchy(
                new DiscoverHierarchyRequest
                {
                    RootTagName = "Missing",
                },
                new TestServerCallContext()));

        Assert.Equal(StatusCode.NotFound, exception.StatusCode);
    }

    private static GalaxyRepositoryGrpcService CreateService(GalaxyHierarchyCacheEntry entry)
    {
        GalaxyRepositoryOptions options = new()
        {
            ConnectionString = "Server=localhost;Database=ZB;Integrated Security=True;Encrypt=False;",
        };
        return new GalaxyRepositoryGrpcService(
            new global::ZB.MOM.WW.MxGateway.Server.Galaxy.GalaxyRepository(options),
            new StubGalaxyHierarchyCache(entry),
            new GalaxyDeployNotifier(),
            new GatewayRequestIdentityAccessor(),
            NullLogger<GalaxyRepositoryGrpcService>.Instance);
    }

    private static GalaxyHierarchyCacheEntry CreateEntry(IReadOnlyList<GalaxyObject> objects)
    {
        return GalaxyHierarchyCacheEntry.Empty with
        {
            Status = GalaxyCacheStatus.Healthy,
            Sequence = 7,
            LastSuccessAt = DateTimeOffset.UtcNow,
            Objects = objects,
            Index = GalaxyHierarchyIndex.Build(objects),
            DashboardSummary = DashboardGalaxySummary.Unknown with
            {
                Status = DashboardGalaxyStatus.Healthy,
                ObjectCount = objects.Count,
            },
            ObjectCount = objects.Count,
        };
    }

    private static IReadOnlyList<GalaxyObject> CreateObjects(int count)
    {
        return Enumerable.Range(1, count)
            .Select(index => new GalaxyObject
            {
                GobjectId = index,
                TagName = $"Object_{index:000}",
                BrowseName = $"Object_{index:000}",
            })
            .ToArray();
    }

    private static IReadOnlyList<GalaxyObject> CreateFilterObjects()
    {
        return
        [
            new GalaxyObject
            {
                GobjectId = 1,
                TagName = "Area1",
                ContainedName = "Area1",
                BrowseName = "Area1",
                IsArea = true,
                CategoryId = 13,
            },
            new GalaxyObject
            {
                GobjectId = 2,
                TagName = "Line3",
                ContainedName = "Line3",
                BrowseName = "Line3",
                ParentGobjectId = 1,
                CategoryId = 10,
                TemplateChain = { "$Line", "$Base" },
            },
            new GalaxyObject
            {
                GobjectId = 3,
                TagName = "Pump_001",
                ContainedName = "Pump",
                BrowseName = "Pump_001",
                ParentGobjectId = 2,
                CategoryId = 10,
                TemplateChain = { "$Pump", "$Base" },
                Attributes =
                {
                    new GalaxyAttribute
                    {
                        AttributeName = "PV",
                        FullTagReference = "Pump_001.PV",
                        IsAlarm = true,
                        IsHistorized = true,
                        SecurityClassification = 2,
                    },
                },
            },
            new GalaxyObject
            {
                GobjectId = 4,
                TagName = "Valve_001",
                ContainedName = "Valve",
                BrowseName = "Valve_001",
                ParentGobjectId = 2,
                CategoryId = 11,
                TemplateChain = { "$Valve" },
                Attributes =
                {
                    new GalaxyAttribute
                    {
                        AttributeName = "PV",
                        FullTagReference = "Valve_001.PV",
                    },
                },
            },
            new GalaxyObject
            {
                GobjectId = 5,
                TagName = "Other_001",
                ContainedName = "Other",
                BrowseName = "Other_001",
                CategoryId = 10,
            },
        ];
    }

    private sealed class StubGalaxyHierarchyCache(GalaxyHierarchyCacheEntry current) : IGalaxyHierarchyCache
    {
        public GalaxyHierarchyCacheEntry Current { get; } = current;

        public Task RefreshAsync(CancellationToken cancellationToken) => Task.CompletedTask;

        public Task WaitForFirstLoadAsync(CancellationToken cancellationToken) => Task.CompletedTask;
    }

}
