using System;
using System.Threading;
using System.Threading.Tasks;
using MessagePack;
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Shared;
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Shared.Contracts;

namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Host.Ipc;

/// <summary>
///     Placeholder handler that responds to the framed IPC with error responses. Replaced by the
///     real Galaxy-backed handler when the MXAccess code move (deferred) lands.
/// </summary>
public sealed class StubFrameHandler : IFrameHandler
{
    public Task HandleAsync(MessageKind kind, byte[] body, FrameWriter writer, CancellationToken ct)
    {
        // Minimal lifecycle: heartbeat ack keeps the supervisor's liveness detector happy even
        // while the data-plane is stubbed, so integration tests of the supervisor can run end-to-end.
        if (kind == MessageKind.Heartbeat)
        {
            var hb = MessagePackSerializer.Deserialize<Heartbeat>(body);
            return writer.WriteAsync(MessageKind.HeartbeatAck,
                new HeartbeatAck { SequenceNumber = hb.SequenceNumber, UtcUnixMs = hb.UtcUnixMs }, ct);
        }

        return writer.WriteAsync(MessageKind.ErrorResponse,
            new ErrorResponse { Code = "not-implemented", Message = $"Kind {kind} is stubbed — MXAccess lift deferred" },
            ct);
    }

    public IDisposable AttachConnection(FrameWriter writer) => IFrameHandler.NoopAttachment.Instance;
}
