/*
 * vl_report_batch.pgc - 심각도별 의심거래 리포트 배치 (커서) (XA).
 *
 * ATMI client: tpinit/tpopen open the ECPG XA RM, tpbegin starts ONE global
 * transaction; the 검증 SELECT/집계 runs on that branch, then tpcommit drives XA 2PC.
 * Usage: vl_report_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "vl_dbio.h"

int main(int argc, char **argv)
{
    long rows = 0; (void)rows; (void)argc; (void)argv;

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_sev[8]; long h_cnt;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, (argc > 1) ? argv[1] : "2026-07-19", 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 rpc CURSOR FOR
        SELECT severity, count(*) FROM vl_suspect
        WHERE biz_date = :h_bizdate GROUP BY severity ORDER BY severity;
    EXEC SQL OPEN rpc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH rpc INTO :h_sev, :h_cnt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE rpc; tpabort(0); return 1; }
        rows++;
    }
    EXEC SQL CLOSE rpc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "vl_report_batch FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> vl_report_batch COMMIT: bizdate=%s 심각도구간=%ld\n", h_bizdate, rows);

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