/*
 * MG_ISO8583.pgc - mg 모듈 서비스 MG_ISO8583 (one service = one file).
 * Split out of the former inline mg_svr.pgc; runs on the caller's XA
 * branch (no EXEC SQL CONNECT). Advertised by mg_svr at tpsvrinit.
 */
#include "MG_ISO8583.h"

/* 3. MG_ISO8583 - ISO8583 전문 파싱 후 로그 (mti=전문 앞 4자리). */
void MG_ISO8583(TPSVCINFO *p)
{
    UBFH *b = (UBFH *)p->data;
    char chan[16], raw[512], bizdate[16], mti[8], proc[8];
    long stan, msg_id, amount, n;

    gets_(b, T_CHANNEL, chan, sizeof(chan)); if (chan[0] == 0) strcpy(chan, "CH01");
    gets_(b, T_STR3, raw, sizeof(raw));
    gets_(b, T_BIZDATE, bizdate, sizeof(bizdate));
    n = (long)strlen(raw);
    /* 고정길이 전문: [0..3]=MTI, [4..9]=처리코드, [10..21]=금액(12자리) */
    memset(mti, 0, sizeof(mti)); memset(proc, 0, sizeof(proc));
    if (n >= 4)  strncpy(mti, raw, 4);
    else         strcpy(mti, "0200");
    if (n >= 10) strncpy(proc, raw + 4, 6);
    else         strcpy(proc, "000000");
    amount = (n >= 22) ? atol(raw + 10) : getl(b, T_AMOUNT);

    stan = mgdb_next_stan();       if (stan < 0) FAIL(b);
    msg_id = mgdb_next_msg_id();   if (msg_id < 0) FAIL(b);
    if (mgdb_insert_msg(msg_id, stan, mti, chan, "IN", proc, "", amount,
                        "", "00", raw, "R", bizdate) < 0) FAIL(b);
    sets_(b, T_STR1, mti);
    sets_(b, T_STR4, proc);
    setl(b, T_AMOUNT, amount);
    setl(b, T_ID1, msg_id);
    OK(b);
}
