/*
 * cm_logroll_batch.pgc - cm 서비스별 로그 롤업 요약행 적재 배치 (XA).
 *
 * ATMI client: tpinit/tpopen open the ECPG XA RM, tpbegin starts ONE global
 * transaction; 기준일 로그를 서비스별로 GROUP BY ... HAVING count(*)>0 집계하여
 * 서비스당 요약(S) 로그 한 건씩을 INSERT ... SELECT 로 재적재; then tpcommit.
 * Usage: cm_logroll_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];
    long h_rows = 0;
    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 INSERT INTO cm_log (log_id, svc_name, log_level, msg, biz_date)
        SELECT nextval('cm_log_seq'), svc_name, 'S', 'ROLLUP', :h_bizdate
        FROM cm_log WHERE biz_date = :h_bizdate
        GROUP BY svc_name HAVING count(*) > 0;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "cm_logroll_batch FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    h_rows = sqlca.sqlerrd[2];

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

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