/*
 * mg_chansnap_batch.pgc - mg 채널 last_stan 커서 갱신 배치 (XA).
 *
 * ATMI client: tpinit/tpopen open the ECPG XA RM, tpbegin starts ONE global
 * transaction; 채널별 최대 STAN 을 커서로 순회하며 mg_channel.last_stan 을
 * 채널마다 행별 UPDATE 로 반영(스냅샷); then tpcommit drives XA 2PC.
 * Usage: mg_chansnap_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";
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_key[32];
    long h_stan = 0;
    EXEC SQL END DECLARE SECTION;
    long updated = 0;

    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 nc CURSOR FOR
        SELECT channel, coalesce(max(stan),0) FROM mg_msg_log
        WHERE biz_date = :h_bizdate GROUP BY channel;
    EXEC SQL OPEN nc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH nc INTO :h_key, :h_stan;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE nc; tpabort(0); return 1; }
        EXEC SQL UPDATE mg_channel SET last_stan = :h_stan WHERE channel = :h_key;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE nc; tpabort(0); return 1; }
        updated += sqlca.sqlerrd[2];
    }
    EXEC SQL CLOSE nc;

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

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