/*
 * vl_sumtxn_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_sumtxn_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "vl_dbio.h"
#include "vl_sumtxn_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], h_merch[64];
    long h_scnt, h_pcnt;
    EXEC SQL END DECLARE SECTION;
    vl_sumtxn_rec_t rec; rec.mismatches = 0;

    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 DECLARE dsm CURSOR FOR
        SELECT ms.merchant_id, ms.txn_count,
               (SELECT count(*) FROM purchase p
                WHERE p.merchant_id = ms.merchant_id AND p.biz_date = ms.biz_date
                  AND p.status <> 'C')
        FROM merchant_summary ms WHERE ms.biz_date = :h_bizdate;
    EXEC SQL OPEN dsm;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH dsm INTO :h_merch, :h_scnt, :h_pcnt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE dsm; tpabort(0); return 1; }
        if (h_scnt != h_pcnt) {
            if (vldb_insert_suspect(0, VL_SUMCNT_RULE, "WARN", "집계-원천 건수 불일치", h_bizdate) < 0) {
                EXEC SQL CLOSE dsm; tpabort(0); return 1;
            }
            rec.mismatches++;
        }
    }
    EXEC SQL CLOSE dsm;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "vl_sumtxn_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; }
    printf(">>> vl_sumtxn_batch COMMIT: bizdate=%s 건수불일치=%ld\n", bizdate, rec.mismatches);

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