using System.Security.Claims;
using Bunit;
using Bunit.TestDoubles;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.Extensions.DependencyInjection;
using NSubstitute;
using ZB.MOM.WW.ScadaBridge.CentralUI.Services;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Audit;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
using ZB.MOM.WW.ScadaBridge.Security;
using ExecutionTreePage = ZB.MOM.WW.ScadaBridge.CentralUI.Components.Pages.Audit.ExecutionTreePage;

namespace ZB.MOM.WW.ScadaBridge.CentralUI.Tests.Pages;

/// <summary>
/// bUnit tests for <see cref="ExecutionTreePage"/> (Audit Log ParentExecutionId
/// feature, Task 10). The page is reached via the "View execution chain"
/// drill-in at <c>/audit/execution-tree?executionId={guid}</c>. It parses the
/// query-string id, calls <see cref="IAuditLogQueryService.GetExecutionTreeAsync"/>,
/// and hands the flat node list to the <c>ExecutionTree</c> component.
/// </summary>
public class ExecutionTreePageTests : BunitContext
{
    private IAuditLogQueryService _queryService = Substitute.For<IAuditLogQueryService>();

    private static ClaimsPrincipal BuildPrincipal(params string[] roles)
    {
        var claims = new List<Claim> { new(JwtTokenService.UsernameClaimType, "tester") };
        claims.AddRange(roles.Select(r => new Claim(JwtTokenService.RoleClaimType, r)));
        return new ClaimsPrincipal(new ClaimsIdentity(claims, "TestAuth"));
    }

    private IRenderedComponent<ExecutionTreePage> RenderPage(string? query, params string[] roles)
    {
        var user = BuildPrincipal(roles);
        Services.AddSingleton<AuthenticationStateProvider>(new TestAuthStateProvider(user));
        Services.AddAuthorizationCore();
        AuthorizationPolicies.AddScadaBridgeAuthorization(Services);
        Services.AddSingleton<IAuthorizationService, DefaultAuthorizationService>();
        Services.AddSingleton(_queryService);

        if (!string.IsNullOrEmpty(query))
        {
            var nav = (BunitNavigationManager)Services.GetRequiredService<NavigationManager>();
            nav.NavigateTo($"/audit/execution-tree?{query}");
        }

        var host = Render<CascadingAuthenticationState>(parameters => parameters
            .Add(p => p.ChildContent, (RenderFragment)(builder =>
            {
                builder.OpenComponent<ExecutionTreePage>(0);
                builder.CloseComponent();
            })));

        return host.FindComponent<ExecutionTreePage>();
    }

    private static ExecutionTreeNode Node(Guid id, Guid? parent, int rowCount = 2)
        => new(
            id, parent, rowCount,
            rowCount == 0 ? Array.Empty<string>() : new[] { "ApiOutbound" },
            rowCount == 0 ? Array.Empty<string>() : new[] { "Delivered" },
            rowCount == 0 ? null : "plant-a",
            rowCount == 0 ? null : "boiler-3",
            rowCount == 0 ? null : new DateTime(2026, 5, 20, 12, 0, 0, DateTimeKind.Utc),
            rowCount == 0 ? null : new DateTime(2026, 5, 20, 12, 0, 5, DateTimeKind.Utc));

    [Fact]
    public void NavigateWithExecutionId_CallsService_AndRendersTree()
    {
        var root = Guid.Parse("11111111-1111-1111-1111-111111111111");
        var child = Guid.Parse("22222222-2222-2222-2222-222222222222");
        _queryService = Substitute.For<IAuditLogQueryService>();
        _queryService.GetExecutionTreeAsync(child, Arg.Any<CancellationToken>())
            .Returns(Task.FromResult<IReadOnlyList<ExecutionTreeNode>>(new List<ExecutionTreeNode>
            {
                Node(root, null),
                Node(child, root),
            }));

        var cut = RenderPage($"executionId={child}", "Administrator");

        cut.WaitForAssertion(() =>
        {
            _queryService.Received().GetExecutionTreeAsync(child, Arg.Any<CancellationToken>());
            Assert.Contains($"data-test=\"tree-node-{root}\"", cut.Markup);
            Assert.Contains($"data-test=\"tree-node-{child}\"", cut.Markup);
        });
    }

    [Fact]
    public void NavigateWithoutExecutionId_RendersGuidancePrompt_NoServiceCall()
    {
        _queryService = Substitute.For<IAuditLogQueryService>();

        var cut = RenderPage(query: null, "Administrator");

        cut.WaitForAssertion(() => Assert.Contains("Execution Chain", cut.Markup));
        _queryService.DidNotReceive().GetExecutionTreeAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
    }

    [Fact]
    public void NavigateWithUnparseableExecutionId_RendersGuidancePrompt_NoServiceCall()
    {
        _queryService = Substitute.For<IAuditLogQueryService>();

        var cut = RenderPage("executionId=not-a-guid", "Administrator");

        cut.WaitForAssertion(() => Assert.Contains("Execution Chain", cut.Markup));
        _queryService.DidNotReceive().GetExecutionTreeAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
    }

    [Fact]
    public void DoubleClickTreeNode_OpensExecutionDetailModal()
    {
        var root = Guid.Parse("33333333-3333-3333-3333-333333333333");
        var child = Guid.Parse("44444444-4444-4444-4444-444444444444");
        _queryService = Substitute.For<IAuditLogQueryService>();
        _queryService.GetExecutionTreeAsync(child, Arg.Any<CancellationToken>())
            .Returns(Task.FromResult<IReadOnlyList<ExecutionTreeNode>>(new List<ExecutionTreeNode>
            {
                Node(root, null),
                Node(child, root),
            }));
        // The modal loads the double-clicked execution's audit rows on open.
        _queryService.QueryAsync(Arg.Any<AuditLogQueryFilter>(), Arg.Any<AuditLogPaging?>(), Arg.Any<CancellationToken>())
            .Returns(Task.FromResult<IReadOnlyList<AuditEventView>>(Array.Empty<AuditEventView>()));
        // AuditEventDetail (reachable from the modal) owns a clipboard interop call.
        JSInterop.Mode = JSRuntimeMode.Loose;

        var cut = RenderPage($"executionId={child}", "Administrator");

        // The modal is absent until a node is activated.
        Assert.Empty(cut.FindAll("[data-test=\"execution-detail-modal\"]"));

        var body = cut.Find($"[data-test=\"tree-node-{child}\"] .execution-tree-body");
        body.DoubleClick();

        cut.WaitForAssertion(() =>
            Assert.NotEmpty(cut.FindAll("[data-test=\"execution-detail-modal\"]")));
        _queryService.Received().QueryAsync(
            Arg.Is<AuditLogQueryFilter>(f => f.ExecutionId == child),
            Arg.Any<AuditLogPaging?>(),
            Arg.Any<CancellationToken>());
    }

    [Fact]
    public void ClosingExecutionDetailModal_HidesIt()
    {
        var root = Guid.Parse("55555555-5555-5555-5555-555555555555");
        var child = Guid.Parse("66666666-6666-6666-6666-666666666666");
        _queryService = Substitute.For<IAuditLogQueryService>();
        _queryService.GetExecutionTreeAsync(child, Arg.Any<CancellationToken>())
            .Returns(Task.FromResult<IReadOnlyList<ExecutionTreeNode>>(new List<ExecutionTreeNode>
            {
                Node(root, null),
                Node(child, root),
            }));
        _queryService.QueryAsync(Arg.Any<AuditLogQueryFilter>(), Arg.Any<AuditLogPaging?>(), Arg.Any<CancellationToken>())
            .Returns(Task.FromResult<IReadOnlyList<AuditEventView>>(Array.Empty<AuditEventView>()));
        JSInterop.Mode = JSRuntimeMode.Loose;

        var cut = RenderPage($"executionId={child}", "Administrator");

        cut.Find($"[data-test=\"tree-node-{child}\"] .execution-tree-body").DoubleClick();
        cut.WaitForAssertion(() =>
            Assert.NotEmpty(cut.FindAll("[data-test=\"execution-detail-modal\"]")));

        cut.Find("[data-test=\"execution-detail-close\"]").Click();

        cut.WaitForAssertion(() =>
            Assert.Empty(cut.FindAll("[data-test=\"execution-detail-modal\"]")));
    }

    [Fact]
    public void ExecutionTreePage_HasOperationalAuditAuthorizeAttribute()
    {
        var attributes = typeof(ExecutionTreePage)
            .GetCustomAttributes(typeof(AuthorizeAttribute), inherit: true)
            .Cast<AuthorizeAttribute>()
            .ToList();

        Assert.Contains(attributes, a => a.Policy == AuthorizationPolicies.OperationalAudit);
    }
}
