using Opc.Ua;

namespace ZB.MOM.WW.OtOpcUa.Client.Shared.Adapters;

/// <summary>
///     Abstracts the OPC UA session for read, write, browse, history, and subscription operations.
/// </summary>
internal interface ISessionAdapter : IDisposable
{
    /// <summary>
    /// Gets a value indicating whether the underlying OPC UA session is currently usable for client operations.
    /// </summary>
    bool Connected { get; }

    /// <summary>
    /// Gets the server-assigned session identifier for diagnostics and failover reporting.
    /// </summary>
    string SessionId { get; }

    /// <summary>
    /// Gets the friendly session name presented to the OPC UA server.
    /// </summary>
    string SessionName { get; }

    /// <summary>
    /// Gets the active endpoint URL that this adapter is connected to.
    /// </summary>
    string EndpointUrl { get; }

    /// <summary>
    /// Gets the server name reported by the connected OPC UA endpoint.
    /// </summary>
    string ServerName { get; }

    /// <summary>
    /// Gets the negotiated OPC UA message security mode for the session.
    /// </summary>
    string SecurityMode { get; }

    /// <summary>
    /// Gets the negotiated OPC UA security policy URI for the session.
    /// </summary>
    string SecurityPolicyUri { get; }

    /// <summary>
    /// Gets the namespace table used to resolve expanded node identifiers returned by browse operations.
    /// </summary>
    NamespaceTable NamespaceUris { get; }

    /// <summary>
    ///     Registers a keep-alive callback. The callback receives true when the session is healthy, false on failure.
    /// </summary>
    /// <param name="callback">The callback used by higher-level clients to trigger reconnect or failover behavior.</param>
    void RegisterKeepAliveHandler(Action<bool> callback);

    /// <summary>
    /// Reads the current value for a node from the connected OPC UA server.
    /// </summary>
    /// <param name="nodeId">The node whose current runtime value should be read.</param>
    /// <param name="ct">The cancellation token that aborts the server read if the client cancels the request.</param>
    /// <returns>The current data value read from the server.</returns>
    Task<DataValue> ReadValueAsync(NodeId nodeId, CancellationToken ct = default);

    /// <summary>
    /// Writes a typed value to a node on the connected OPC UA server.
    /// </summary>
    /// <param name="nodeId">The node whose value should be updated.</param>
    /// <param name="value">The typed OPC UA data value to write to the server.</param>
    /// <param name="ct">The cancellation token that aborts the write if the client cancels the request.</param>
    /// <returns>The status code returned by the server for the write operation.</returns>
    Task<StatusCode> WriteValueAsync(NodeId nodeId, DataValue value, CancellationToken ct = default);

    /// <summary>
    ///     Browses forward hierarchical references from the given node.
    ///     Returns (continuationPoint, references).
    /// </summary>
    /// <param name="nodeId">The starting node for the hierarchical browse.</param>
    /// <param name="nodeClassMask">The node classes that should be returned to the caller.</param>
    /// <param name="ct">The cancellation token that aborts the browse request.</param>
    /// <returns>A continuation point (or <c>null</c> when complete) and the references found.</returns>
    Task<(byte[]? ContinuationPoint, ReferenceDescriptionCollection References)> BrowseAsync(
        NodeId nodeId, uint nodeClassMask = 0, CancellationToken ct = default);

    /// <summary>
    ///     Continues a browse from a continuation point.
    /// </summary>
    /// <param name="continuationPoint">The continuation token returned by a prior browse result page.</param>
    /// <param name="ct">The cancellation token that aborts the browse-next request.</param>
    /// <returns>The next continuation point (or <c>null</c> when exhausted) and the additional references.</returns>
    Task<(byte[]? ContinuationPoint, ReferenceDescriptionCollection References)> BrowseNextAsync(
        byte[] continuationPoint, CancellationToken ct = default);

    /// <summary>
    ///     Checks whether a node has any forward hierarchical child references.
    /// </summary>
    /// <param name="nodeId">The node to inspect for child objects or variables.</param>
    /// <param name="ct">The cancellation token that aborts the child lookup.</param>
    /// <returns><c>true</c> when the node has at least one forward hierarchical child reference; otherwise <c>false</c>.</returns>
    Task<bool> HasChildrenAsync(NodeId nodeId, CancellationToken ct = default);

    /// <summary>
    ///     Reads raw historical data.
    /// </summary>
    /// <param name="nodeId">The historized node whose raw samples should be retrieved.</param>
    /// <param name="startTime">The inclusive start of the requested history window.</param>
    /// <param name="endTime">The inclusive end of the requested history window.</param>
    /// <param name="maxValues">The maximum number of raw samples to return to the client.</param>
    /// <param name="ct">The cancellation token that aborts the history read.</param>
    /// <returns>The raw historical data values for the requested window.</returns>
    Task<IReadOnlyList<DataValue>> HistoryReadRawAsync(NodeId nodeId, DateTime startTime, DateTime endTime,
        int maxValues, CancellationToken ct = default);

    /// <summary>
    ///     Reads processed/aggregate historical data.
    /// </summary>
    /// <param name="nodeId">The historized node whose processed values should be retrieved.</param>
    /// <param name="startTime">The inclusive start of the requested processed-history window.</param>
    /// <param name="endTime">The inclusive end of the requested processed-history window.</param>
    /// <param name="aggregateId">The OPC UA aggregate function to evaluate over the history window.</param>
    /// <param name="intervalMs">The processing interval, in milliseconds, for each aggregate bucket.</param>
    /// <param name="ct">The cancellation token that aborts the aggregate history read.</param>
    /// <returns>The processed/aggregate data values for the requested window.</returns>
    Task<IReadOnlyList<DataValue>> HistoryReadAggregateAsync(NodeId nodeId, DateTime startTime, DateTime endTime,
        NodeId aggregateId, double intervalMs, CancellationToken ct = default);

    /// <summary>
    ///     Creates a subscription adapter for this session.
    /// </summary>
    /// <param name="publishingIntervalMs">The requested publishing interval for monitored items on the new subscription.</param>
    /// <param name="ct">The cancellation token that aborts subscription creation.</param>
    /// <returns>The newly created subscription adapter.</returns>
    Task<ISubscriptionAdapter> CreateSubscriptionAsync(int publishingIntervalMs, CancellationToken ct = default);

    /// <summary>
    /// Calls an OPC UA method node with the provided input arguments.
    /// </summary>
    /// <param name="objectId">The object node that owns the target method.</param>
    /// <param name="methodId">The method node to invoke.</param>
    /// <param name="inputArguments">The ordered input arguments supplied to the server method call.</param>
    /// <param name="ct">The cancellation token that aborts the method invocation.</param>
    /// <returns>The output arguments returned by the method call.</returns>
    Task<IList<object>?> CallMethodAsync(NodeId objectId, NodeId methodId, object[] inputArguments, CancellationToken ct = default);

    /// <summary>
    /// Closes the underlying session gracefully before the adapter is disposed or replaced during failover.
    /// </summary>
    /// <param name="ct">The cancellation token that aborts the close request.</param>
    /// <returns>A task that represents the asynchronous operation.</returns>
    Task CloseAsync(CancellationToken ct = default);
}
