/*
 * vl_cancelrate_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_cancelrate_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "vl_dbio.h"
#include "vl_cancelrate_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_bizdate[16];
    long h_pcnt, h_ccnt;
    EXEC SQL END DECLARE SECTION;
    vl_cancelrate_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 count(*) INTO :h_pcnt FROM purchase WHERE biz_date = :h_bizdate;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "SEL1 FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }
    EXEC SQL SELECT count(*) INTO :h_ccnt FROM ac_cancel WHERE biz_date = :h_bizdate;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "vl_cancelrate_batch FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    rec.pcnt = h_pcnt; rec.ccnt = h_ccnt;
    rec.pct = (h_pcnt > 0) ? (h_ccnt * 100 / h_pcnt) : 0;
    if (rec.pct >= VL_CXLRATE_THR) {
        if (vldb_insert_suspect(0, VL_CXLRATE_RULE, "WARN", "취소율 과다", h_bizdate) < 0) {
            tpabort(0); return 1;
        }
    }

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> vl_cancelrate_batch COMMIT: bizdate=%s 매입=%ld 취소=%ld 취소율=%ld%%\n",
           bizdate, rec.pcnt, rec.ccnt, rec.pct);

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