/*
 * mg_resend_batch.pgc - mg 실패 전문 재전송 배치 (커서 + XA).
 *
 * ATMI client: tpinit/tpopen open the ECPG XA RM, tpbegin starts ONE global
 * transaction, an EXEC SQL cursor sweeps mg_queue rows in F(실패)/Q(대기) state
 * for a biz_date, re-queues each (status->Q, retry_cnt++) via the linked dbio
 * lib, then tpcommit drives XA 2PC. Usage: mg_resend_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "mg_dbio.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    long rows = 0;

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_qid, h_retry;
    EXEC SQL END DECLARE SECTION;

    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 DECLARE rsc CURSOR FOR
        SELECT queue_id, retry_cnt FROM mg_queue
        WHERE biz_date = :h_bizdate AND status = 'F'
        ORDER BY queue_id;
    EXEC SQL OPEN rsc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH rsc INTO :h_qid, :h_retry;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE rsc; tpabort(0); return 1; }
        /* 실패 전문을 재전송 대기(Q)로 되돌리고 retry_cnt 증가 */
        EXEC SQL UPDATE mg_queue
            SET status = 'Q', retry_cnt = retry_cnt + 1, updated_at = now()
            WHERE queue_id = :h_qid;
        if (sqlca.sqlcode < 0 || sqlca.sqlcode == 100) { EXEC SQL CLOSE rsc; tpabort(0); return 1; }
        rows++;
    }
    EXEC SQL CLOSE rsc;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> mg_resend_batch COMMIT: bizdate=%s resent=%ld\n", bizdate, rows);

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