using Microsoft.AspNetCore.Components.Authorization;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Management;
using ZB.MOM.WW.ScadaBridge.Communication;
using ZB.MOM.WW.ScadaBridge.Security;

namespace ZB.MOM.WW.ScadaBridge.CentralUI.Services;

/// <summary>
/// Default <see cref="ICertManagementService"/> implementation — a thin facade over
/// the three <see cref="CommunicationService"/> cert-trust relay methods that enforces
/// the CentralUI-side role trust boundary (Trust + Remove require
/// <c>Administrator</c>, List requires <c>Designer</c>), and translates transport
/// exceptions into a typed <see cref="CertTrustResult"/>.
/// </summary>
/// <remarks>
/// Site-side actors (<c>SiteCommunicationActor</c> + <c>DeploymentManagerActor</c>) do
/// not unwrap the central trust envelope, so the role check MUST run here — never on
/// the site (mirrors <see cref="BrowseService"/> and <see cref="EndpointVerificationService"/>).
/// On an unauthorized caller the method returns a non-success
/// <see cref="CertTrustResult"/> with <c>"Not authorized."</c> rather than throwing;
/// transport failures (timeouts, unreachable sites) collapse into a non-success result
/// so the editor / page can render an inline outcome.
/// </remarks>
public sealed class CertManagementService : ICertManagementService
{
    private readonly CommunicationService _communication;
    private readonly AuthenticationStateProvider _auth;

    /// <summary>
    /// Initializes a new instance of the <see cref="CertManagementService"/>.
    /// </summary>
    /// <param name="communication">Central-side cluster communication service.</param>
    /// <param name="auth">Authentication state provider used for the role guards.</param>
    public CertManagementService(CommunicationService communication, AuthenticationStateProvider auth)
    {
        _communication = communication ?? throw new ArgumentNullException(nameof(communication));
        _auth = auth ?? throw new ArgumentNullException(nameof(auth));
    }

    /// <inheritdoc/>
    public async Task<CertTrustResult> TrustAsync(
        string siteIdentifier,
        string connectionName,
        string derBase64,
        string thumbprint,
        CancellationToken cancellationToken = default)
    {
        // Trusting a server certificate mutates every site node's PKI store, so
        // it is an Administrator-only action. The site does not enforce envelope-level
        // roles, so this check must happen here before any cross-cluster traffic.
        if (!await HasRoleAsync(Roles.Administrator))
        {
            return new CertTrustResult(false, "Not authorized.", null);
        }

        try
        {
            return await _communication.TrustServerCertAsync(
                siteIdentifier,
                new TrustServerCertCommand(connectionName, derBase64, thumbprint),
                cancellationToken);
        }
        catch (TimeoutException ex)
        {
            return new CertTrustResult(false, ex.Message, null);
        }
        catch (OperationCanceledException)
        {
            // Caller-initiated cancel — propagate so Blazor can drop the response
            // cleanly. Distinct from Timeout (which the UI renders inline).
            throw;
        }
        catch (Exception ex)
        {
            return new CertTrustResult(false, ex.Message, null);
        }
    }

    /// <inheritdoc/>
    public async Task<CertTrustResult> ListAsync(
        string siteIdentifier,
        CancellationToken cancellationToken = default)
    {
        // Listing trusted certs is read-only, so the lower Designer bar applies
        // (an Administrator also satisfies this because admins hold every role claim
        // by convention). Same CentralUI-side guard rationale as TrustAsync.
        if (!await HasRoleAsync(Roles.Designer))
        {
            return new CertTrustResult(false, "Not authorized.", null);
        }

        try
        {
            return await _communication.ListServerCertsAsync(
                siteIdentifier, new ListServerCertsCommand(), cancellationToken);
        }
        catch (TimeoutException ex)
        {
            return new CertTrustResult(false, ex.Message, null);
        }
        catch (OperationCanceledException)
        {
            throw;
        }
        catch (Exception ex)
        {
            return new CertTrustResult(false, ex.Message, null);
        }
    }

    /// <inheritdoc/>
    public async Task<CertTrustResult> RemoveAsync(
        string siteIdentifier,
        string thumbprint,
        CancellationToken cancellationToken = default)
    {
        // Removing trust mutates every site node's PKI store, so it is an
        // Administrator-only action — same gate as TrustAsync.
        if (!await HasRoleAsync(Roles.Administrator))
        {
            return new CertTrustResult(false, "Not authorized.", null);
        }

        try
        {
            return await _communication.RemoveServerCertAsync(
                siteIdentifier, new RemoveServerCertCommand(thumbprint), cancellationToken);
        }
        catch (TimeoutException ex)
        {
            return new CertTrustResult(false, ex.Message, null);
        }
        catch (OperationCanceledException)
        {
            throw;
        }
        catch (Exception ex)
        {
            return new CertTrustResult(false, ex.Message, null);
        }
    }

    private async Task<bool> HasRoleAsync(string role)
    {
        var state = await _auth.GetAuthenticationStateAsync();
        return state.User.HasClaim(JwtTokenService.RoleClaimType, role);
    }
}
