/*
 * vl_thrtrim_batch.pgc - 검증 규칙 임계값 정리 배치 (XA 단일 글로벌 트랜잭션 배치).
 *
 * ATMI client: tpinit/tpopen open the ECPG XA RM, tpbegin starts ONE global
 * transaction; 잘못 저장된 음수 임계값을 0으로 클램프하고 전체 규칙 수를
 * 함께 보고한 뒤 tpcommit drives XA 2PC.
 * Usage: vl_thrtrim_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "vl_thrtrim_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_total;
    EXEC SQL END DECLARE SECTION;
    vl_thrtrim_rec_t rec;
    (void)bizdate;

    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_rule SET threshold = 0, updated_at = now()
        WHERE threshold < 0;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "vl_thrtrim_batch FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    rec.clamped = (long)sqlca.sqlerrd[2];
    EXEC SQL SELECT count(*) INTO :h_total FROM vl_rule;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "vl_thrtrim_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.total_rules = h_total;
    printf(">>> vl_thrtrim_batch COMMIT: 음수임계값정리=%ld 전체규칙=%ld\n",
           rec.clamped, rec.total_rules);

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