/*
 * MG_DEQUEUE.pgc - mg 모듈 서비스 MG_DEQUEUE (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_DEQUEUE.h"

/* 25. MG_DEQUEUE - 대기(Q) 전문 1건 인출 후 송신중(S) 전이. */
void MG_DEQUEUE(TPSVCINFO *p)
{
    UBFH *b = (UBFH *)p->data;
    EXEC SQL BEGIN DECLARE SECTION;
    long h_qid, h_stan;
    char h_payload[512], h_chan[16];
    EXEC SQL END DECLARE SECTION;

    EXEC SQL SELECT queue_id, stan, channel, payload INTO :h_qid, :h_stan, :h_chan, :h_payload
        FROM mg_queue WHERE status = 'Q' ORDER BY queue_id ASC LIMIT 1;
    if (sqlca.sqlcode == 100) { setl(b, T_COUNT, 0); OK(b); }
    if (sqlca.sqlcode < 0) FAIL(b);

    EXEC SQL UPDATE mg_queue SET status = 'S', updated_at = now() WHERE queue_id = :h_qid;
    if (sqlca.sqlcode < 0 || sqlca.sqlcode == 100) FAIL(b);

    setl(b, T_ID2, h_qid);
    setl(b, T_ARG1, h_stan);
    sets_(b, T_CHANNEL, h_chan);
    sets_(b, T_STR3, h_payload);
    setl(b, T_COUNT, 1);
    OK(b);
}
