/*
 * vl_daterev_batch.pgc - 일자 역전 검출 배치 (XA 단일 글로벌 트랜잭션 배치).
 *
 * ATMI client: tpinit/tpopen open the ECPG XA RM, tpbegin starts ONE global
 * transaction; 매입일보다 과거로 기표된 정산/원장 건수를 각각 집계한 뒤
 * tpcommit drives XA 2PC.
 * Usage: vl_daterev_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "vl_daterev_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : VL_DATEREV_DEF_DATE;
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_srev, h_lrev;
    EXEC SQL END DECLARE SECTION;
    vl_daterev_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_srev
        FROM settlement s JOIN purchase p ON p.purchase_id = s.purchase_id
        WHERE s.biz_date = :h_bizdate AND s.biz_date < p.biz_date;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "vl_daterev_batch FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    EXEC SQL SELECT count(*) INTO :h_lrev
        FROM ledger l JOIN purchase p ON p.purchase_id = l.purchase_id
        WHERE l.biz_date = :h_bizdate AND l.biz_date < p.biz_date;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "vl_daterev_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.settle_rev = h_srev; rec.ledger_rev = h_lrev;
    printf(">>> vl_daterev_batch COMMIT: bizdate=%s 정산역전=%ld 원장역전=%ld\n",
           bizdate, rec.settle_rev, rec.ledger_rev);

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