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;
///
/// 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.
///
public class ExternalSystemFormAuditDrillinTests : BunitContext
{
private readonly IExternalSystemRepository _repo = Substitute.For();
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(new TestAuthStateProvider(user));
Services.AddAuthorizationCore();
AuthorizationPolicies.AddScadaBridgeAuthorization(Services);
}
[Fact]
public void EditPage_HasRecentAuditActivityLink_WithTargetEqualToSystemName()
{
_repo.GetExternalSystemByIdAsync(7, Arg.Any())
.Returns(new ExternalSystemDefinition("ERP-Alpha", "https://erp.example.test", "ApiKey")
{
Id = 7,
});
var cut = Render(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();
cut.WaitForAssertion(() =>
{
Assert.Empty(cut.FindAll("a[data-test=\"audit-link\"]"));
});
}
}