/*
 * vl_sumrecon_batch.pgc - 가맹점 일별 통계-원천 대사 배치 (XA 단일 글로벌 트랜잭션 배치).
 *
 * ATMI client: tpinit/tpopen open the ECPG XA RM, tpbegin starts ONE global
 * transaction; merchant_summary의 건수/총액을 purchase 원천 재집계와 대조해
 * 불일치 행 수를 산출한 뒤 tpcommit drives XA 2PC.
 * Usage: vl_sumrecon_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "vl_sumrecon_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : VL_SUMRECON_DEF_DATE;
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_rows, h_mis;
    EXEC SQL END DECLARE SECTION;
    vl_sumrecon_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_rows FROM merchant_summary
        WHERE biz_date = :h_bizdate;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "vl_sumrecon_batch FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    EXEC SQL SELECT count(*) INTO :h_mis FROM merchant_summary ms
        WHERE ms.biz_date = :h_bizdate
          AND (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')
           OR  ms.gross_amount <> coalesce((SELECT sum(p.amount) FROM purchase p
                                            WHERE p.merchant_id = ms.merchant_id
                                              AND p.biz_date = ms.biz_date
                                              AND p.status <> 'C'), 0));
    if (sqlca.sqlcode < 0) { fprintf(stderr, "vl_sumrecon_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.summary_rows = h_rows; rec.mismatched = h_mis;
    printf(">>> vl_sumrecon_batch COMMIT: bizdate=%s 통계행=%ld 대사불일치=%ld\n",
           bizdate, rec.summary_rows, rec.mismatched);

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