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

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

/// <summary>
///     Placeholder handler that returns <c>ErrorResponse{Code=not-implemented}</c> for every
///     FOCAS data-plane request. Exists so PR B can ship the pipe server + ACL + handshake
///     plumbing before PR C moves the Fwlib32 calls. Heartbeats are handled fully so the
///     supervisor's liveness detector stays happy.
/// </summary>
public sealed class StubFrameHandler : IFrameHandler
{
    public Task HandleAsync(FocasMessageKind kind, byte[] body, FrameWriter writer, CancellationToken ct)
    {
        if (kind == FocasMessageKind.Heartbeat)
        {
            var hb = MessagePackSerializer.Deserialize<Heartbeat>(body);
            return writer.WriteAsync(FocasMessageKind.HeartbeatAck,
                new HeartbeatAck
                {
                    MonotonicTicks = hb.MonotonicTicks,
                    HostUtcUnixMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
                }, ct);
        }

        return writer.WriteAsync(FocasMessageKind.ErrorResponse,
            new ErrorResponse
            {
                Code = "not-implemented",
                Message = $"Kind {kind} is stubbed — Fwlib32 lift lands in PR C",
            },
            ct);
    }

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