/*
 * vl_agedopen_batch.pgc - 장기미결 의심거래 에스컬레이션 배치 (XA 단일 글로벌 트랜잭션 배치).
 *
 * ATMI client: tpinit/tpopen open the ECPG XA RM, tpbegin starts ONE global
 * transaction; N일 초과 OPEN 의심거래의 severity를 CRIT로 승격한 뒤
 * tpcommit drives XA 2PC.
 * Usage: vl_agedopen_batch [YYYY-MM-DD] [경과일수]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "vl_agedopen_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    EXEC SQL BEGIN DECLARE SECTION;
    long h_days;
    EXEC SQL END DECLARE SECTION;
    vl_agedopen_rec_t rec;
    (void)bizdate;

    h_days = (argc > 2) ? atol(argv[2]) : VL_AGEDOPEN_DEF_DAYS;
    if (h_days <= 0) h_days = VL_AGEDOPEN_DEF_DAYS;

    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 = 'CRIT'
        WHERE status = 'OPEN' AND severity <> 'CRIT'
          AND created_at < now() - (:h_days || ' days')::interval;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "vl_agedopen_batch FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    rec.escalated = (long)sqlca.sqlerrd[2];

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    rec.days = h_days;
    printf(">>> vl_agedopen_batch COMMIT: 기준=%ld일 CRIT승격=%ld\n", rec.days, rec.escalated);

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