/*
 * vl_wfstat_batch.pgc - 의심거래 워크플로 상태 통계 배치 (XA 단일 글로벌 트랜잭션 배치).
 *
 * ATMI client: tpinit/tpopen open the ECPG XA RM, tpbegin starts ONE global
 * transaction; 일자별 의심거래를 확인/조치/종결 워크플로 상태별로 집계한 뒤
 * tpcommit drives XA 2PC.
 * Usage: vl_wfstat_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "vl_wfstat_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : VL_WFSTAT_DEF_DATE;
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_open, h_conf, h_closed;
    EXEC SQL END DECLARE SECTION;
    vl_wfstat_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
        coalesce(sum(CASE WHEN status = 'OPEN'      THEN 1 ELSE 0 END),0),
        coalesce(sum(CASE WHEN status = 'CONFIRMED' THEN 1 ELSE 0 END),0),
        coalesce(sum(CASE WHEN status = 'CLOSED'    THEN 1 ELSE 0 END),0)
        INTO :h_open, :h_conf, :h_closed
        FROM vl_suspect WHERE biz_date = :h_bizdate;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "vl_wfstat_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.open_c = h_open; rec.conf_c = h_conf; rec.closed_c = h_closed;
    printf(">>> vl_wfstat_batch COMMIT: bizdate=%s 미결=%ld 확인=%ld 종결=%ld\n",
           bizdate, rec.open_c, rec.conf_c, rec.closed_c);

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