using System.Security.Claims;
using Bunit;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.JSInterop;
using NSubstitute;
using ScadaLink.Commons.Entities.InboundApi;
using ScadaLink.Commons.Interfaces.Repositories;
using ScadaLink.Security;
using ApiKeyForm = ScadaLink.CentralUI.Components.Pages.Admin.ApiKeyForm;
namespace ScadaLink.CentralUI.Tests.Admin;
///
/// Bundle D drill-in test (#23 M7-T12) for the API Keys edit page. The chip
/// routes operators into the central Audit Log pre-filtered by Actor = ApiKey.Name
/// AND Channel = ApiInbound (no other channel uses the key name as actor, but
/// the explicit channel scope keeps deep links tight). Create mode suppresses
/// the link — there's no API key to drill into yet.
///
public class ApiKeyFormAuditDrillinTests : BunitContext
{
private readonly IInboundApiRepository _repo = Substitute.For();
public ApiKeyFormAuditDrillinTests()
{
Services.AddSingleton(_repo);
var claims = new[]
{
new Claim("Username", "admin"),
new Claim(JwtTokenService.RoleClaimType, "Admin"),
};
var user = new ClaimsPrincipal(new ClaimsIdentity(claims, "TestAuth"));
Services.AddSingleton(new TestAuthStateProvider(user));
Services.AddAuthorizationCore();
AuthorizationPolicies.AddScadaLinkAuthorization(Services);
}
[Fact]
public void EditPage_HasRecentAuditActivityLink_WithActorAndApiInboundChannel()
{
var key = ApiKey.FromHash("Orders-Integration", "k-hash");
key.Id = 11;
_repo.GetApiKeyByIdAsync(11, Arg.Any()).Returns(key);
_repo.GetAllApiMethodsAsync(Arg.Any())
.Returns(Task.FromResult>(new List()));
var cut = Render(p => p.Add(c => c.Id, 11));
cut.WaitForAssertion(() =>
{
var link = cut.Find("a[data-test=\"audit-link\"]");
Assert.Equal(
"/audit/log?actor=Orders-Integration&channel=ApiInbound",
link.GetAttribute("href"));
Assert.Contains("Recent audit activity", link.TextContent);
});
}
[Fact]
public void CreatePage_HasNoRecentAuditActivityLink()
{
var cut = Render();
cut.WaitForAssertion(() =>
{
Assert.Empty(cut.FindAll("a[data-test=\"audit-link\"]"));
});
}
}