@page "/certificates"
@attribute [Authorize(Policy = AdminUiPolicies.AuthenticatedRead)]
@rendermode RenderMode.InteractiveServer
@using System.Security.Cryptography.X509Certificates
@using Microsoft.Extensions.Configuration
@using Microsoft.AspNetCore.Components.Authorization
@using ZB.MOM.WW.OtOpcUa.AdminUI.Certificates
@inject IConfiguration Config
@inject CertificateStoreManager CertManager
@inject Microsoft.AspNetCore.Authorization.IAuthorizationService AuthorizationService
@inject AuthenticationStateProvider AuthState
@implements IDisposable

<div class="d-flex justify-content-between align-items-center mb-3">
    <h4 class="mb-0">OPC UA certificates</h4>
</div>

<section class="panel notice rise" style="animation-delay:.02s">
    PKI store layout: <span class="mono">{PkiStoreRoot}/own</span> (this server's identity),
    <span class="mono">issuer</span> / <span class="mono">trusted</span> (peers we accept),
    <span class="mono">rejected</span> (peers we've turned away). F13a wires SDK
    auto-creation so the own-store self-signs on first boot.
</section>

@if (_rows is null)
{
    <p class="mt-3">Loading…</p>
}
else
{
    @if (_statusMsg is not null)
    {
        <section class="panel notice rise mt-3" style="@(_statusError ? "border-color:var(--alert)" : null)">@_statusMsg</section>
    }
    @if (_pending is { } p)
    {
        <section class="panel notice rise mt-3">
            Confirm <strong>@p.Verb</strong> of <span class="mono small">@p.Subject</span>?
            <button class="btn btn-sm btn-primary" @onclick="ConfirmAction">Confirm</button>
            <button class="btn btn-sm btn-outline-secondary" @onclick="CancelAction">Cancel</button>
        </section>
    }
    @foreach (var store in _rows)
    {
        <section class="panel rise mt-3" style="animation-delay:.08s">
            <div class="panel-head">@store.Label &middot; @store.Certificates.Count entry@(store.Certificates.Count == 1 ? "" : "s")</div>
            @if (string.IsNullOrEmpty(store.Path))
            {
                <div style="padding:1rem" class="text-muted">No path configured.</div>
            }
            else if (!Directory.Exists(store.Path))
            {
                <div style="padding:1rem" class="text-muted">
                    <span class="mono">@store.Path</span> doesn't exist yet. It will be created on first boot.
                </div>
            }
            else if (store.Certificates.Count == 0)
            {
                <div style="padding:1rem" class="text-muted">No certificates in <span class="mono">@store.Path</span>.</div>
            }
            else
            {
                <div class="table-wrap">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>Subject</th>
                                <th>Issuer</th>
                                <th>Thumbprint</th>
                                <th>Not before</th>
                                <th>Not after</th>
                                @if (store.Kind is StoreKind.Trusted or StoreKind.Rejected)
                                {
                                    <th>Actions</th>
                                }
                            </tr>
                        </thead>
                        <tbody>
                            @foreach (var c in store.Certificates)
                            {
                                <tr>
                                    <td><span class="mono small">@c.Subject</span></td>
                                    <td><span class="mono small">@c.Issuer</span></td>
                                    <td><span class="mono small">@c.Thumbprint[..16]…</span></td>
                                    <td>@c.NotBefore.ToString("u")</td>
                                    <td>@c.NotAfter.ToString("u")</td>
                                    @if (store.Kind is StoreKind.Trusted or StoreKind.Rejected)
                                    {
                                        <td>
                                            <AuthorizeView Policy="@AdminUiPolicies.FleetAdmin">
                                                <Authorized>
                                                    @if (store.Kind == StoreKind.Rejected)
                                                    {
                                                        <button class="btn btn-sm btn-outline-primary" @onclick='() => RequestAction(store.Kind, c, "trust")'>Trust</button>
                                                    }
                                                    else
                                                    {
                                                        <button class="btn btn-sm btn-outline-secondary" @onclick='() => RequestAction(store.Kind, c, "untrust")'>Untrust</button>
                                                    }
                                                    <button class="btn btn-sm btn-outline-danger" @onclick='() => RequestAction(store.Kind, c, "delete")'>Delete</button>
                                                </Authorized>
                                            </AuthorizeView>
                                        </td>
                                    }
                                </tr>
                            }
                        </tbody>
                    </table>
                </div>
            }
        </section>
    }
}

@code {
    private List<StoreView>? _rows;

    private enum StoreKind { Own, Trusted, Issuer, Rejected }
    private sealed record StoreView(string Label, StoreKind Kind, string Path, List<X509Certificate2> Certificates);

    private (StoreKind Kind, string Thumbprint, string Subject, string Verb)? _pending;
    private string? _statusMsg;
    private bool _statusError;

    protected override void OnInitialized() => LoadAll();

    private void LoadAll()
    {
        DisposeRows();
        var pkiRoot = CertManager.PkiRoot; // Single source: manager already resolved OpcUa:PkiStoreRoot (default "pki").
        _rows = new()
        {
            LoadStore("Own", StoreKind.Own, Path.Combine(pkiRoot, "own", "certs")),
            LoadStore("Trusted peers", StoreKind.Trusted, Path.Combine(pkiRoot, "trusted", "certs")),
            LoadStore("Trusted issuers", StoreKind.Issuer, Path.Combine(pkiRoot, "issuer", "certs")),
            LoadStore("Rejected", StoreKind.Rejected, Path.Combine(pkiRoot, "rejected", "certs")),
        };
        _pending = null;
    }

    private void DisposeRows()
    {
        if (_rows is null) return;
        foreach (var store in _rows)
            foreach (var c in store.Certificates)
                c.Dispose();
    }

    public void Dispose() => DisposeRows();

    private static StoreView LoadStore(string label, StoreKind kind, string path)
    {
        var view = new StoreView(label, kind, path, new List<X509Certificate2>());
        if (!Directory.Exists(path)) return view;
        foreach (var file in Directory.EnumerateFiles(path).Where(IsCertFile))
        {
            try { view.Certificates.Add(X509CertificateLoader.LoadCertificateFromFile(file)); }
            catch { /* ignore unreadable entries */ }
        }
        return view;
    }

    private static bool IsCertFile(string path)
    {
        var ext = Path.GetExtension(path);
        return ext.Equals(".der", StringComparison.OrdinalIgnoreCase)
            || ext.Equals(".cer", StringComparison.OrdinalIgnoreCase)
            || ext.Equals(".crt", StringComparison.OrdinalIgnoreCase);
    }

    private void RequestAction(StoreKind kind, X509Certificate2 cert, string verb)
    {
        _pending = (kind, cert.Thumbprint!, cert.Subject, verb);
        _statusMsg = null;
    }

    private void CancelAction() => _pending = null;

    private async Task ConfirmAction()
    {
        if (_pending is not { } p) return;

        // Defense-in-depth: the action buttons are FleetAdmin-gated in markup, but this handler
        // runs on the server circuit — re-check the policy before mutating the trust store.
        var authState = await AuthState.GetAuthenticationStateAsync();
        if (!(await AuthorizationService.AuthorizeAsync(authState.User, null, AdminUiPolicies.FleetAdmin)).Succeeded)
        {
            _statusError = true;
            _statusMsg = "Unauthorized — FleetAdmin required.";
            _pending = null;
            return;
        }

        var actor = authState.User.Identity?.Name ?? "system";
        var result = p.Verb switch
        {
            "trust"   => CertManager.Trust(p.Thumbprint, actor),
            "untrust" => CertManager.Untrust(p.Thumbprint, actor),
            "delete"  => p.Kind switch
            {
                StoreKind.Trusted  => CertManager.Delete("trusted", p.Thumbprint, actor),
                StoreKind.Rejected => CertManager.Delete("rejected", p.Thumbprint, actor),
                // Unreachable defensive guard — action buttons only render for Trusted/Rejected stores
                // + the 3 literal verbs (Trust/Untrust/Delete); this arm never executes, so it
                // intentionally does not route through CertificateStoreManager/audit.
                _                  => CertActionResult.Fail($"cannot delete from {p.Kind}"),
            },
            // Unreachable defensive guard — action buttons only render for Trusted/Rejected stores
            // + the 3 literal verbs (Trust/Untrust/Delete); this arm never executes, so it
            // intentionally does not route through CertificateStoreManager/audit.
            _ => CertActionResult.Fail("unknown action"),
        };
        _statusError = !result.Success;
        _statusMsg = result.Success
            ? $"{char.ToUpper(p.Verb[0])}{p.Verb[1..]} of {p.Subject} succeeded."
            : $"{p.Verb} failed: {result.Error}";
        LoadAll(); // clears _pending
    }
}
