/*
 * cm_svcsnap_batch.pgc - cm 서비스별 스냅샷 마커 조건부 적재 배치 (XA).
 *
 * ATMI client: tpinit/tpopen open the ECPG XA RM, tpbegin starts ONE global
 * transaction; 서비스별 log_id 합을 커서로 순회하며 합이 0보다 큰 서비스에만
 * (if 가드) cm_log 스냅샷(S) 마커를 행별 INSERT; then tpcommit.
 * Usage: cm_svcsnap_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "cm_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_amt = 0;
    EXEC SQL END DECLARE SECTION;
    long inserted = 0, skipped = 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 sc CURSOR FOR
        SELECT svc_name, coalesce(sum(log_id),0) FROM cm_log
        WHERE biz_date = :h_bizdate GROUP BY svc_name;
    EXEC SQL OPEN sc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH sc INTO :h_key, :h_amt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE sc; tpabort(0); return 1; }
        if (h_amt > 0) {
            EXEC SQL INSERT INTO cm_log (log_id, svc_name, log_level, msg, biz_date)
                VALUES (nextval('cm_log_seq'), :h_key, 'S', 'SNAP', :h_bizdate);
            if (sqlca.sqlcode < 0) { EXEC SQL CLOSE sc; tpabort(0); return 1; }
            inserted++;
        } else {
            skipped++;
        }
    }
    EXEC SQL CLOSE sc;

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

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