/*
 * py_recon_batch.pgc - py 지급집계 대사 (집계 vs 실집계 2-쿼리 대조 배치, XA).
 *
 * Compares the stored py_summary amount against the live py_payout sum for one
 * merchant/day and reports the gap, all inside ONE XA transaction.
 * Usage: py_recon_batch MERCHANT [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "py_recon_batch.h"

int main(int argc, char **argv)
{
    const char *merch   = (argc > 1) ? argv[1] : "M0001";
    const char *bizdate = (argc > 2) ? argv[2] : "2026-07-19";
    py_recon_rec_t rec;

    EXEC SQL BEGIN DECLARE SECTION;
    char h_merch[64], h_bizdate[16];
    long h_rec, h_live;
    EXEC SQL END DECLARE SECTION;

    strncpy(h_merch, merch, sizeof(h_merch)-1); h_merch[sizeof(h_merch)-1] = 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 SELECT coalesce(payout_amount,0) INTO :h_rec FROM py_summary
        WHERE merchant_id = :h_merch AND biz_date = :h_bizdate;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "py_recon_batch sum FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    if (sqlca.sqlcode == 100) h_rec = 0;
    EXEC SQL SELECT coalesce(sum(amount),0) INTO :h_live FROM py_payout
        WHERE merchant_id = :h_merch AND biz_date = :h_bizdate;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "py_recon_batch live 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; }

    strncpy(rec.merchant_id, merch, sizeof(rec.merchant_id)-1); rec.merchant_id[sizeof(rec.merchant_id)-1] = 0;
    rec.recorded_amt = h_rec; rec.live_amt = h_live; rec.gap = h_live - h_rec;
    printf(">>> py_recon_batch COMMIT: merch=%s date=%s recorded=%ld live=%ld gap=%ld\n",
           rec.merchant_id, bizdate, rec.recorded_amt, rec.live_amt, rec.gap);

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