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.InboundApi;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Security;
using ZB.MOM.WW.ScadaBridge.Security;
using ApiKeyForm = ZB.MOM.WW.ScadaBridge.CentralUI.Components.Pages.Admin.ApiKeyForm;

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

/// <summary>
/// Bundle D drill-in test (#23 M7-T12) for the API Keys edit page, re-wired for the
/// inbound-API-key re-arch (C3) onto the <see cref="IInboundApiKeyAdmin"/> seam. The chip
/// routes operators into the central Audit Log pre-filtered by Actor = key 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. Also covers the new seam-driven list and one-time-token panel.
/// </summary>
public class ApiKeyFormAuditDrillinTests : BunitContext
{
    private readonly IInboundApiKeyAdmin _admin = Substitute.For<IInboundApiKeyAdmin>();
    private readonly IInboundApiRepository _repo = Substitute.For<IInboundApiRepository>();

    public ApiKeyFormAuditDrillinTests()
    {
        Services.AddSingleton(_admin);
        Services.AddSingleton(_repo);

        // Methods still come from the SQL Server repository; default to none unless a test overrides.
        _repo.GetAllApiMethodsAsync(Arg.Any<CancellationToken>())
            .Returns(Task.FromResult<IReadOnlyList<ApiMethod>>(new List<ApiMethod>()));

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

    private static InboundApiKeyInfo Key(
        string keyId, string name, bool enabled = true, params string[] methods) =>
        new(keyId, name, enabled, methods, DateTimeOffset.UnixEpoch, null);

    [Fact]
    public void EditPage_HasRecentAuditActivityLink_WithActorAndApiInboundChannel()
    {
        const string keyId = "abc123def456";
        var info = Key(keyId, "Orders-Integration", true, "PlaceOrder");
        _admin.ListAsync(Arg.Any<CancellationToken>())
            .Returns(Task.FromResult<IReadOnlyList<InboundApiKeyInfo>>(new[] { info }));
        _admin.GetMethodsForKeyAsync(keyId, Arg.Any<CancellationToken>())
            .Returns(Task.FromResult<IReadOnlyList<string>>(new[] { "PlaceOrder" }));

        var cut = Render<ApiKeyForm>(p => p.Add(c => c.KeyId, keyId));

        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()
    {
        _admin.ListAsync(Arg.Any<CancellationToken>())
            .Returns(Task.FromResult<IReadOnlyList<InboundApiKeyInfo>>(Array.Empty<InboundApiKeyInfo>()));

        var cut = Render<ApiKeyForm>();

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

    [Fact]
    public async Task CreatePage_WithMethodSelected_ShowsOneTimeTokenAndKeyId()
    {
        _admin.ListAsync(Arg.Any<CancellationToken>())
            .Returns(Task.FromResult<IReadOnlyList<InboundApiKeyInfo>>(Array.Empty<InboundApiKeyInfo>()));
        _repo.GetAllApiMethodsAsync(Arg.Any<CancellationToken>())
            .Returns(Task.FromResult<IReadOnlyList<ApiMethod>>(
                new List<ApiMethod> { new("PlaceOrder", "return null;") { Id = 1 } }));
        _admin.CreateAsync("MES-Production", Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>())
            .Returns(Task.FromResult(new InboundApiKeyCreated("new-key-id", "sbk_new-key-id_secret")));

        var cut = Render<ApiKeyForm>();

        // Fill name, check the only method, save.
        cut.WaitForElement("input[type=text]").Change("MES-Production");
        cut.Find("#method-access-1").Change(true);
        await cut.Find("button.btn-success").ClickAsync(new());

        cut.WaitForAssertion(() =>
        {
            var token = cut.Find("[data-test=\"created-token\"]");
            Assert.Contains("sbk_new-key-id_secret", token.TextContent);
            Assert.Contains("new-key-id", cut.Markup);
            Assert.Contains("will not be shown again", cut.Markup);
        });

        await _admin.Received(1).CreateAsync(
            "MES-Production",
            Arg.Is<IReadOnlyCollection<string>>(m => m.Count == 1 && m.Contains("PlaceOrder")),
            Arg.Any<CancellationToken>());
    }

    [Fact]
    public async Task CreatePage_WithNoMethodSelected_ShowsValidationError_AndDoesNotCreate()
    {
        _admin.ListAsync(Arg.Any<CancellationToken>())
            .Returns(Task.FromResult<IReadOnlyList<InboundApiKeyInfo>>(Array.Empty<InboundApiKeyInfo>()));
        _repo.GetAllApiMethodsAsync(Arg.Any<CancellationToken>())
            .Returns(Task.FromResult<IReadOnlyList<ApiMethod>>(
                new List<ApiMethod> { new("PlaceOrder", "return null;") { Id = 1 } }));

        var cut = Render<ApiKeyForm>();
        cut.WaitForElement("input[type=text]").Change("MES-Production");
        await cut.Find("button.btn-success").ClickAsync(new());

        cut.WaitForAssertion(() =>
            Assert.Contains("at least one API method", cut.Markup));

        await _admin.DidNotReceive().CreateAsync(
            Arg.Any<string>(), Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>());
    }
}
