/*
 * vl_axis_recon_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_axis_recon_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "vl_dbio.h"
#include "vl_axis_recon_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : VL_AXIS_DEF_DATE;
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_pnet, h_snet;
    EXEC SQL END DECLARE SECTION;
    vl_axis_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 coalesce(sum(net),0) INTO :h_pnet FROM purchase
        WHERE biz_date = :h_bizdate AND status = 'S';
    if (sqlca.sqlcode < 0) { fprintf(stderr, "SEL1 FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }
    EXEC SQL SELECT coalesce(sum(net),0) INTO :h_snet FROM settlement
        WHERE biz_date = :h_bizdate;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "vl_axis_recon_batch FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    rec.pnet = h_pnet; rec.snet = h_snet;
    if (h_pnet != h_snet) {
        if (vldb_insert_suspect(0, VL_AXIS_RULE, "ERROR", "매입-정산 축 총액 불일치", h_bizdate) < 0) {
            fprintf(stderr, "insert_suspect FAIL\n"); tpabort(0); return 1;
        }
    }

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> vl_axis_recon_batch COMMIT: bizdate=%s 매입순액=%ld 정산순액=%ld delta=%ld\n",
           bizdate, rec.pnet, rec.snet, rec.pnet - rec.snet);

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