/*
 * vl_tristage_batch.pgc - 매입-정산-지급 3단 정합 대사 배치 (XA 단일 글로벌 트랜잭션 배치).
 *
 * ATMI client: tpinit/tpopen open the ECPG XA RM, tpbegin starts ONE global
 * transaction; 정산완료 매입 순액/정산 순액/지급(XFER) 원장 합계와 건별 3단
 * 불일치 건수를 집계한 뒤 tpcommit drives XA 2PC.
 * Usage: vl_tristage_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "vl_tristage_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : VL_TRISTAGE_DEF_DATE;
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_pnet, h_snet, h_xamt, h_bad;
    EXEC SQL END DECLARE SECTION;
    vl_tristage_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, "vl_tristage_batch FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); 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_tristage_batch FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    EXEC SQL SELECT coalesce(sum(amount),0) INTO :h_xamt FROM ledger
        WHERE biz_date = :h_bizdate AND entry_type = 'XFER';
    if (sqlca.sqlcode < 0) { fprintf(stderr, "vl_tristage_batch FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    EXEC SQL SELECT count(*) INTO :h_bad FROM purchase p
        WHERE p.biz_date = :h_bizdate AND p.status = 'S'
          AND (p.net <> coalesce((SELECT sum(s.net) FROM settlement s
                                  WHERE s.purchase_id = p.purchase_id), 0)
           OR  p.net <> coalesce((SELECT sum(l.amount) FROM ledger l
                                  WHERE l.purchase_id = p.purchase_id
                                    AND l.entry_type = 'XFER'), 0));
    if (sqlca.sqlcode < 0) { fprintf(stderr, "vl_tristage_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.p_net = h_pnet; rec.s_net = h_snet; rec.x_amt = h_xamt; rec.broken = h_bad;
    printf(">>> vl_tristage_batch COMMIT: bizdate=%s 매입=%ld 정산=%ld 지급=%ld 3단불일치=%ld\n",
           bizdate, rec.p_net, rec.s_net, rec.x_amt, rec.broken);

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