/*
 * vl_suspesc_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_suspesc_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "vl_dbio.h"
#include "vl_suspesc_batch.h"

int main(int argc, char **argv)
{
    long age = (argc > 2) ? atol(argv[2]) : VL_SUSPESC_AGE;
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19"; (void)bizdate;
    EXEC SQL BEGIN DECLARE SECTION;
    long h_age, h_rows;
    EXEC SQL END DECLARE SECTION;
    vl_suspesc_rec_t rec;
    h_age = (age > 0) ? age : VL_SUSPESC_AGE;

    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 UPDATE vl_suspect SET severity = 'ERROR'
        WHERE status = 'OPEN' AND severity = 'WARN'
          AND biz_date < current_date - CAST(:h_age AS int);
    if (sqlca.sqlcode < 0) { fprintf(stderr, "vl_suspesc_batch FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    h_rows = (long)sqlca.sqlerrd[2];
    rec.escalated = h_rows;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> vl_suspesc_batch COMMIT: 경과일>%ld 자동상향=%ld건\n", h_age, rec.escalated);

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