/*
 * vl_ruleaudit_batch.pgc - 검증 규칙 감사 배치 (XA 단일 글로벌 트랜잭션 배치).
 *
 * ATMI client: tpinit/tpopen open the ECPG XA RM, tpbegin starts ONE global
 * transaction; 커서로 임계값이 설정되지 않은 ACTIVE 고위험(ERROR/CRIT) 규칙을
 * 훑어 규칙별로 검증로그에 남긴 뒤 tpcommit drives XA 2PC.
 * Usage: vl_ruleaudit_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "vl_dbio.h"
#include "vl_ruleaudit_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_rule[64];
    EXEC SQL END DECLARE SECTION;
    char detail[96];
    vl_ruleaudit_rec_t rec; rec.bad_rules = 0; rec.logged = 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 DECLARE vrac CURSOR FOR
        SELECT rule_code FROM vl_rule
        WHERE status = 'ACTIVE' AND severity IN ('ERROR','CRIT')
          AND threshold <= 0
        ORDER BY rule_code;
    EXEC SQL OPEN vrac;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "vl_ruleaudit_batch OPEN FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH vrac INTO :h_rule;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "vl_ruleaudit_batch FETCH FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }
        rec.bad_rules++;
        snprintf(detail, sizeof(detail), "%s 임계값 미설정 고위험 규칙", h_rule);
        if (vldb_insert_check_log(VL_RULEAUDIT_CHECK, 0, 1, detail, bizdate) < 0) {
            fprintf(stderr, "vl_ruleaudit_batch 검증로그 적재 FAIL\n"); tpabort(0); return 1;
        }
        rec.logged++;
    }
    EXEC SQL CLOSE vrac;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> vl_ruleaudit_batch COMMIT: bizdate=%s 감사적발규칙=%ld 로그=%ld\n",
           bizdate, rec.bad_rules, rec.logged);

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