using ZB.MOM.WW.MxGateway.Contracts.Proto;

namespace ZB.MOM.WW.MxGateway.Server.Workers;

/// <summary>
/// Validates worker envelope messages against protocol expectations.
/// </summary>
internal static class WorkerEnvelopeValidator
{
    /// <summary>
    /// Validates a worker envelope for protocol compliance.
    /// </summary>
    /// <param name="envelope">The envelope to validate.</param>
    /// <param name="options">The frame protocol configuration.</param>
    public static void Validate(
        WorkerEnvelope envelope,
        WorkerFrameProtocolOptions options)
    {
        if (envelope.ProtocolVersion != options.ProtocolVersion)
        {
            throw new WorkerFrameProtocolException(
                WorkerFrameProtocolErrorCode.ProtocolVersionMismatch,
                $"Worker envelope protocol version {envelope.ProtocolVersion} does not match expected version {options.ProtocolVersion}.");
        }

        if (!string.Equals(envelope.SessionId, options.SessionId, StringComparison.Ordinal))
        {
            throw new WorkerFrameProtocolException(
                WorkerFrameProtocolErrorCode.SessionMismatch,
                "Worker envelope session id does not match the owning gateway session.");
        }

        if (envelope.BodyCase == WorkerEnvelope.BodyOneofCase.None)
        {
            throw new WorkerFrameProtocolException(
                WorkerFrameProtocolErrorCode.InvalidEnvelope,
                "Worker envelope must include a typed body.");
        }
    }
}
