/*
 * util_msg.c - 고정길이 전문 pack/unpack 유틸리티 (plain C, 공유)
 */
#include "acq_util.h"

#include <string.h>
#include <ctype.h>

void msg_field_copy(char *out, const char *field, int len)
{
    int end;
    if (!out || !field || len < 0)
        return;
    end = len;
    while (end > 0 && (field[end - 1] == ' ' || field[end - 1] == '\0'))
        end--;
    memcpy(out, field, end);
    out[end] = '\0';
}

void msg_field_set(char *field, const char *src, int len)
{
    int slen, i;
    if (!field || len < 0)
        return;
    slen = src ? (int)strlen(src) : 0;
    if (slen > len)
        slen = len;
    memcpy(field, src, slen);
    for (i = slen; i < len; i++)
        field[i] = ' ';
}

void msg_field_set_num(char *field, const char *src, int len)
{
    int slen, pad, i;
    if (!field || len < 0)
        return;
    slen = src ? (int)strlen(src) : 0;
    if (slen > len)
        slen = len;
    pad = len - slen;
    for (i = 0; i < pad; i++)
        field[i] = '0';
    if (src)
        memcpy(field + pad, src, slen);
}

int msg_unpack(acq_msg_t *msg, const char *raw, int rawlen)
{
    if (!msg || !raw)
        return -1;
    if (rawlen < MSG_ACQ_LEN)
        return -1;
    memcpy(msg, raw, MSG_ACQ_LEN);
    return 0;
}

int msg_pack(const acq_msg_t *msg, char *raw, int rawlen)
{
    if (!msg || !raw)
        return -1;
    if (rawlen < MSG_ACQ_LEN)
        return -1;
    memcpy(raw, msg, MSG_ACQ_LEN);
    return 0;
}

static int field_blank(const char *field, int len)
{
    int i;
    for (i = 0; i < len; i++)
        if (field[i] != ' ' && field[i] != '\0')
            return 0;
    return 1;
}

int msg_validate(const acq_msg_t *msg)
{
    if (!msg)
        return -1;
    if (field_blank(msg->msg_type, FLD_MSG_TYPE_LEN)) return -1;
    if (field_blank(msg->merch_id, FLD_MERCH_ID_LEN)) return -1;
    if (field_blank(msg->card_no, FLD_CARD_NO_LEN)) return -1;
    if (field_blank(msg->amount, FLD_AMOUNT_LEN)) return -1;
    if (field_blank(msg->txn_date, FLD_TXN_DATE_LEN)) return -1;
    return 0;
}
