using ZB.MOM.WW.OtOpcUa.ControlPlane.Redundancy;
using ZB.MOM.WW.OtOpcUa.Security.Auth;

namespace ZB.MOM.WW.OtOpcUa.AdminUI.Redundancy;

/// <summary>
/// Presentation state for the Trigger-failover control on the cluster redundancy page.
/// </summary>
/// <remarks>
///     <para>
///         A pure model behind a thin razor shell — the same split the driver-typed tag editors use,
///         and for the same reason: this repo has no bUnit (see
///         <c>PageAuthorizationGuardTests</c>), so anything left inside the <c>.razor</c> is verified
///         only by driving the page live. The peer guard, the confirm flow, and the
///         refused-vs-succeeded outcome are consequential enough to be unit-testable, so they live
///         here.
///     </para>
///     <para>
///         What is deliberately NOT here: the markup authorization gate. It is expressed in the razor
///         as <c>&lt;AuthorizeView Policy="@ManualFailoverPageModel.RequiredPolicy"&gt;</c> and
///         re-checked server-side before the call, so <see cref="RequiredPolicy"/> is the single
///         source of truth for both.
///     </para>
/// </remarks>
public sealed class ManualFailoverPageModel
{
    /// <summary>
    /// The policy gating the control, in markup and in the server-side re-check.
    /// </summary>
    /// <remarks>
    /// <see cref="AdminUiPolicies.FleetAdmin"/> (Administrator only) rather than the
    /// <see cref="AdminUiPolicies.ConfigEditor"/> the neighbouring cluster-authoring pages use:
    /// this does not edit configuration, it restarts a production node. ConfigEditor also admits the
    /// Designer role, which must not be able to bounce the Primary.
    /// </remarks>
    public const string RequiredPolicy = AdminUiPolicies.FleetAdmin;

    private readonly IManualFailoverService _service;

    /// <summary>Creates the model over the failover service.</summary>
    /// <param name="service">The manual-failover seam; faked in tests.</param>
    public ManualFailoverPageModel(IManualFailoverService service)
        => _service = service ?? throw new ArgumentNullException(nameof(service));

    /// <summary>The last read cluster snapshot, or <see langword="null"/> if it could not be read.</summary>
    public ManualFailoverSnapshot? Snapshot { get; private set; }

    /// <summary>Whether the confirmation dialog is open.</summary>
    public bool ConfirmOpen { get; private set; }

    /// <summary>Status text from the last completed action, if any.</summary>
    public string? StatusMessage { get; private set; }

    /// <summary>Whether <see cref="StatusMessage"/> reports a failure.</summary>
    public bool StatusIsError { get; private set; }

    /// <summary>Whether the button is enabled — a peer must exist to take over.</summary>
    public bool CanFailOver => Snapshot?.CanFailOver == true;

    /// <summary>
    /// Why the button is disabled, or <see langword="null"/> when it is enabled. Rendered as the
    /// button's tooltip so a disabled control explains itself.
    /// </summary>
    public string? DisabledReason => Snapshot is null
        ? "Cluster state is unavailable on this node."
        : Snapshot.CanFailOver
            ? null
            : $"Failover needs a driver peer to take over; this mesh has {Snapshot.DriverAddresses.Count} Up driver member(s).";

    /// <summary>Re-reads live cluster state. Never throws — an unreadable cluster disables the button.</summary>
    public void Refresh()
    {
        try
        {
            Snapshot = _service.GetSnapshot();
        }
        catch (Exception ex)
        {
            // A node whose ActorSystem is not yet up (or not a cluster provider) must render the page,
            // not 500. The button stays disabled with DisabledReason explaining why.
            Snapshot = null;
            StatusIsError = true;
            StatusMessage = $"Could not read cluster state: {ex.Message}";
        }
    }

    /// <summary>Opens the confirmation dialog. No-op when the peer guard is closed.</summary>
    public void RequestFailover()
    {
        if (!CanFailOver) return;
        StatusMessage = null;
        StatusIsError = false;
        ConfirmOpen = true;
    }

    /// <summary>Closes the confirmation dialog without acting.</summary>
    public void CancelFailover() => ConfirmOpen = false;

    /// <summary>
    /// Performs the failover the dialog is confirming.
    /// </summary>
    /// <param name="actor">The authenticated user name, recorded in the audit event.</param>
    public async Task ConfirmFailoverAsync(string actor)
    {
        if (!ConfirmOpen) return;
        ConfirmOpen = false;

        try
        {
            var target = await _service.FailOverDriverPrimaryAsync(actor).ConfigureAwait(false);
            if (target is null)
            {
                // The service re-evaluates the peer guard against live state, which may have changed
                // since Refresh(). A refusal is not an error — but it must not read as a success.
                StatusIsError = true;
                StatusMessage = "Failover refused: no driver peer is available to take over.";
            }
            else
            {
                StatusIsError = false;
                StatusMessage =
                    $"Failover requested. {target} is leaving the cluster; its peer takes over as Primary "
                    + "and the node restarts as the youngest member.";
            }
        }
        catch (Exception ex)
        {
            StatusIsError = true;
            StatusMessage = $"Failover failed: {ex.Message}";
        }

        Refresh();
    }
}
