using System.Linq;
using System.Security.Claims;
using Bunit;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.Extensions.DependencyInjection;
using NSubstitute;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.ExternalSystems;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
using ZB.MOM.WW.ScadaBridge.Security;
using ExternalSystemForm = ZB.MOM.WW.ScadaBridge.CentralUI.Components.Pages.Design.ExternalSystemForm;

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

/// <summary>
/// Bundle D drill-in test (#23 M7-T12) for the External Systems edit page.
/// The page-header chip routes operators into the central Audit Log
/// pre-filtered by Target = external-system name. Create mode has nothing
/// to drill into yet, so the link is suppressed.
/// </summary>
public class ExternalSystemFormAuditDrillinTests : BunitContext
{
    private readonly IExternalSystemRepository _repo = Substitute.For<IExternalSystemRepository>();

    public ExternalSystemFormAuditDrillinTests()
    {
        Services.AddSingleton(_repo);

        var claims = new[]
        {
            new Claim(JwtTokenService.UsernameClaimType, "tester"),
            new Claim(JwtTokenService.RoleClaimType, "Designer"),
        };
        var user = new ClaimsPrincipal(new ClaimsIdentity(claims, "TestAuth"));
        Services.AddSingleton<AuthenticationStateProvider>(new TestAuthStateProvider(user));
        Services.AddAuthorizationCore();
        AuthorizationPolicies.AddScadaBridgeAuthorization(Services);
    }

    [Fact]
    public void EditPage_HasRecentAuditActivityLink_WithTargetEqualToSystemName()
    {
        _repo.GetExternalSystemByIdAsync(7, Arg.Any<CancellationToken>())
            .Returns(new ExternalSystemDefinition("ERP-Alpha", "https://erp.example.test", "ApiKey")
            {
                Id = 7,
            });

        var cut = Render<ExternalSystemForm>(p => p.Add(c => c.Id, 7));

        cut.WaitForAssertion(() =>
        {
            var link = cut.Find("a[data-test=\"audit-link\"]");
            Assert.Equal("/audit/log?target=ERP-Alpha", link.GetAttribute("href"));
            Assert.Contains("Recent audit activity", link.TextContent);
        });
    }

    [Fact]
    public void CreatePage_HasNoRecentAuditActivityLink()
    {
        // Create mode (Id is null) — there's no real external system to drill into,
        // so the link must not render.
        var cut = Render<ExternalSystemForm>();

        cut.WaitForAssertion(() =>
        {
            Assert.Empty(cut.FindAll("a[data-test=\"audit-link\"]"));
        });
    }

    [Fact]
    public void Form_RendersTimeoutSecondsInput_WithGatewayDefaultHelperText()
    {
        // PLAN-06 Task 12: the per-system TimeoutSeconds column (Task 8) needs a
        // Central UI form field so Design users can actually set it.
        var cut = Render<ExternalSystemForm>();

        cut.WaitForAssertion(() =>
        {
            Assert.Contains("Timeout (seconds)", cut.Markup);
            Assert.Contains("0 = use gateway default", cut.Markup);
        });
    }

    [Fact]
    public void SavingNewSystem_WithTimeoutSeconds_PassesTimeoutSecondsToRepository()
    {
        var cut = Render<ExternalSystemForm>();

        // Re-query between each Change(): two-way binding re-renders the form and
        // invalidates previously found element references.
        cut.FindAll("input[type=text]")[0].Change("ERP-Beta");                          // Name
        cut.FindAll("input[type=text]")[1].Change("https://erp-beta.example.test");     // Endpoint URL
        cut.FindAll("input[type=number]")[2].Change("20");                              // Timeout (seconds)

        cut.FindAll("button").First(b => b.TextContent.Contains("Save")).Click();

        cut.WaitForAssertion(() =>
        {
            _repo.Received().AddExternalSystemAsync(
                Arg.Is<ExternalSystemDefinition>(e => e.TimeoutSeconds == 20));
            _repo.Received().SaveChangesAsync();
        });
    }

    [Fact]
    public void SavingEditedSystem_UpdatesTimeoutSecondsOnExisting()
    {
        var existing = new ExternalSystemDefinition("ERP-Delta", "https://erp-delta.example.test", "ApiKey")
        {
            Id = 11,
            TimeoutSeconds = 10,
        };
        _repo.GetExternalSystemByIdAsync(11, Arg.Any<CancellationToken>()).Returns(existing);

        var cut = Render<ExternalSystemForm>(p => p.Add(c => c.Id, 11));
        cut.WaitForState(() => cut.FindAll("input[type=number]").Count >= 3);

        // The Timeout field must be pre-filled from the existing entity on load.
        Assert.Contains(cut.FindAll("input[type=number]"), i => i.GetAttribute("value") == "10");

        cut.FindAll("input[type=number]")[2].Change("60"); // Timeout (seconds)
        cut.FindAll("button").First(b => b.TextContent.Contains("Save")).Click();

        cut.WaitForAssertion(() =>
        {
            Assert.Equal(60, existing.TimeoutSeconds);
            _repo.Received().UpdateExternalSystemAsync(existing);
        });
    }
}
