/*
 * vl_feerecalc_batch.pgc - 수수료 재계산 편차 검증 배치 (XA 단일 글로벌 트랜잭션 배치).
 *
 * ATMI client: tpinit/tpopen open the ECPG XA RM, tpbegin starts ONE global
 * transaction; 가맹점 요율로 수수료를 재계산해 허용오차를 넘는 매입 건수와
 * 편차 총액을 집계한 뒤 tpcommit drives XA 2PC.
 * Usage: vl_feerecalc_batch [YYYY-MM-DD] [허용오차원]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "vl_feerecalc_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_tol, h_viol, h_devsum;
    EXEC SQL END DECLARE SECTION;
    vl_feerecalc_rec_t rec;

    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    h_tol = (argc > 2) ? atol(argv[2]) : VL_FEERECALC_DEF_TOL;
    if (h_tol < 0) h_tol = VL_FEERECALC_DEF_TOL;

    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(*),
                    coalesce(sum(abs(p.fee - p.amount * m.mdr_bps / 10000)),0)
        INTO :h_viol, :h_devsum
        FROM purchase p JOIN merchant m ON m.merchant_id = p.merchant_id
        WHERE p.biz_date = :h_bizdate
          AND abs(p.fee - p.amount * m.mdr_bps / 10000) > :h_tol;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "vl_feerecalc_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.tol_won = h_tol; rec.viol = h_viol; rec.dev_sum = h_devsum;
    printf(">>> vl_feerecalc_batch COMMIT: bizdate=%s 허용=%ld원 편차초과=%ld 편차합=%ld\n",
           bizdate, rec.tol_won, rec.viol, rec.dev_sum);

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