/*
 * vl_errgrp_batch.pgc - vl 반복 에러코드 그룹 집계 배치 (XA 단일 글로벌 트랜잭션 배치).
 *
 * ATMI client: tpinit/tpopen open the ECPG XA RM, tpbegin starts ONE global
 * transaction, EXEC SQL runs on the biz_date, then tpcommit drives XA 2PC.
 * Usage: vl_errgrp_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "vl_errgrp_batch.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_min = 2, h_groups = 0;
    EXEC SQL END DECLARE SECTION;
    vl_errgrp_rec_t rec;

    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 SELECT count(*) INTO :h_groups FROM (
        SELECT result_code FROM vl_check_log
        WHERE biz_date = :h_bizdate AND result_code > 0
        GROUP BY result_code HAVING count(*) >= :h_min) t;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "vl_errgrp_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; }
    rec.threshold = h_min; rec.groups = h_groups;
    printf(">>> vl_errgrp_batch COMMIT: bizdate=%s 임계=%ld 반복에러그룹=%ld\n", bizdate, rec.threshold, rec.groups);

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