using Microsoft.AspNetCore.Components.Authorization;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Protocol;
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="IBrowseService"/> implementation — a thin facade over
/// <see cref="CommunicationService.BrowseNodeAsync"/> that enforces the
/// CentralUI-side <c>Design</c>-role trust boundary and translates transport
/// exceptions into a typed <see cref="BrowseFailure"/> result.
/// </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. Transport failures collapse into <c>Timeout</c> or
/// <c>ServerError</c> so the dialog can show an inline banner while leaving the
/// manual node-id paste field usable.
/// </remarks>
public sealed class BrowseService : IBrowseService
{
    private readonly CommunicationService _communication;
    private readonly AuthenticationStateProvider _auth;

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

    /// <inheritdoc/>
    public async Task<BrowseNodeResult> BrowseChildrenAsync(
        string siteId,
        string connectionName,
        string? parentNodeId,
        string? continuationToken = null,
        CancellationToken cancellationToken = default)
    {
        // CentralUI-side role guard — sites don't enforce envelope-level roles,
        // so the Designer check must happen here before any cross-cluster traffic.
        var state = await _auth.GetAuthenticationStateAsync();
        if (!state.User.HasClaim(JwtTokenService.RoleClaimType, Roles.Designer))
        {
            return new BrowseNodeResult(
                Array.Empty<BrowseNode>(),
                Truncated: false,
                new BrowseFailure(BrowseFailureKind.ServerError, "Not authorized."));
        }

        try
        {
            return await _communication.BrowseNodeAsync(
                siteId,
                new BrowseNodeCommand(connectionName, parentNodeId, continuationToken),
                cancellationToken);
        }
        catch (TimeoutException ex)
        {
            // Akka Ask timed out — the site (or its OPC UA session) didn't answer
            // within CommunicationOptions.QueryTimeout. Surface as a typed
            // Timeout failure so the dialog can render an inline banner.
            return new BrowseNodeResult(
                Array.Empty<BrowseNode>(),
                Truncated: false,
                new BrowseFailure(BrowseFailureKind.Timeout, ex.Message));
        }
        catch (OperationCanceledException)
        {
            // Caller-initiated cancel — propagate so Blazor can drop the response
            // cleanly. Distinct from Timeout (which the dialog renders inline).
            throw;
        }
        catch (Exception ex)
        {
            // Any other transport / serialization failure: keep the dialog
            // alive and let the user fall back to manual node-id paste.
            return new BrowseNodeResult(
                Array.Empty<BrowseNode>(),
                Truncated: false,
                new BrowseFailure(BrowseFailureKind.ServerError, ex.Message));
        }
    }

    /// <inheritdoc/>
    public async Task<SearchAddressSpaceResult> SearchAsync(
        string siteId,
        string connectionName,
        string query,
        int maxDepth,
        int maxResults,
        CancellationToken cancellationToken = default)
    {
        // Same CentralUI-side role guard as BrowseChildrenAsync — sites don't
        // enforce envelope-level roles, so the Designer check must happen here
        // before any cross-cluster traffic.
        var state = await _auth.GetAuthenticationStateAsync();
        if (!state.User.HasClaim(JwtTokenService.RoleClaimType, Roles.Designer))
        {
            return new SearchAddressSpaceResult(
                Array.Empty<AddressSpaceMatch>(),
                CapReached: false,
                new BrowseFailure(BrowseFailureKind.ServerError, "Not authorized."));
        }

        try
        {
            return await _communication.SearchAddressSpaceAsync(
                siteId,
                new SearchAddressSpaceCommand(connectionName, query, maxDepth, maxResults),
                cancellationToken);
        }
        catch (TimeoutException ex)
        {
            // Akka Ask timed out — the site (or its OPC UA session) didn't answer
            // within CommunicationOptions.QueryTimeout. Surface as a typed Timeout
            // failure so the picker can render an inline banner.
            return new SearchAddressSpaceResult(
                Array.Empty<AddressSpaceMatch>(),
                CapReached: false,
                new BrowseFailure(BrowseFailureKind.Timeout, ex.Message));
        }
        catch (OperationCanceledException)
        {
            // Caller-initiated cancel — propagate so Blazor can drop the response
            // cleanly. Distinct from Timeout (which the picker renders inline).
            throw;
        }
        catch (Exception ex)
        {
            // Any other transport / serialization failure: keep the picker alive
            // and let the user fall back to manual browse / node-id paste.
            return new SearchAddressSpaceResult(
                Array.Empty<AddressSpaceMatch>(),
                CapReached: false,
                new BrowseFailure(BrowseFailureKind.ServerError, ex.Message));
        }
    }
}
