// assignment_request.cpp — see assignment_request.h. Pure: standard library only.

#include "core/wire/assignment_request.h"

#include "core/wire/wire.h"

namespace reasampler::wire {

namespace {

constexpr const char* kMagic = "rsassign1";

using wire::putField;
using Cursor = wire::Cursor;

}  // namespace

std::string encodeAssignmentRequest(const AssignmentRequest& req) {
    std::string out = kMagic;
    putField(out, req.bankId);
    putField(out, req.sampleId);
    putField(out, std::to_string(req.generation));
    return out;
}

std::optional<AssignmentRequest> decodeAssignmentRequest(const std::string& wire) {
    Cursor cur(wire);
    if (!cur.literal(kMagic)) return std::nullopt;

    AssignmentRequest req;
    if (!cur.field(req.bankId)) return std::nullopt;
    if (!cur.field(req.sampleId)) return std::nullopt;
    if (!cur.fieldInt64(req.generation)) return std::nullopt;

    // Reject trailing garbage: a well-formed value ends exactly at the last field.
    if (!cur.ok() || !cur.atEnd()) return std::nullopt;
    return req;
}

}  // namespace reasampler::wire
