/*
 * mg_requeue_batch.pgc - mg 응답오류 전문 재전송 큐 적재 배치 (XA 단일 글로벌 트랜잭션 배치).
 *
 * ATMI client: tpinit/tpopen open the ECPG XA RM, tpbegin starts ONE global
 * transaction, EXEC SQL runs on the biz_date, then tpcommit drives XA 2PC.
 * Usage: mg_requeue_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "mg_requeue_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    EXEC SQL END DECLARE SECTION;
    mg_requeue_rec_t rec;

    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;

    if (tpinit(NULL) < 0) { fprintf(stderr, "tpinit FAIL: %s\n", tpstrerror(tperrno)); return 1; }
    if (tpopen() < 0)     { fprintf(stderr, "tpopen FAIL: %s\n", tpstrerror(tperrno)); return 1; }
    if (tpbegin(60, 0) < 0) { fprintf(stderr, "tpbegin FAIL: %s\n", tpstrerror(tperrno)); return 1; }

    EXEC SQL INSERT INTO mg_queue
        (queue_id, stan, channel, mti, payload, status, biz_date)
        SELECT nextval('mg_queue_seq'), m.stan, m.channel, m.mti, m.raw_msg, 'Q', m.biz_date
        FROM mg_msg_log m
        WHERE m.biz_date = :h_bizdate AND m.rc <> '00' AND m.direction = 'IN';
    if (sqlca.sqlcode < 0) { fprintf(stderr, "mg_requeue_batch FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    rec.requeued = (long) sqlca.sqlerrd[2];

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> mg_requeue_batch COMMIT: bizdate=%s 재적재=%ld\n", bizdate, rec.requeued);

    tpclose(); tpterm();
    return 0;
}
