/*
 * lg_reversepair_batch.pgc - lg 역분개 상쇄 집계 (EXISTS 상관 배치, XA).
 *
 * Counts POST vouchers that have a matching REVERSE voucher via a correlated
 * EXISTS subquery, inside ONE XA transaction.
 * Usage: lg_reversepair_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "lg_reversepair_batch.h"

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

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_cnt;
    EXEC SQL END DECLARE SECTION;

    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_cnt FROM lg_voucher v
        WHERE v.voucher_type = 'POST' AND v.biz_date = :h_bizdate
          AND EXISTS (SELECT 1 FROM lg_voucher r
                      WHERE r.voucher_type = 'REVERSE' AND r.ref_id = v.voucher_id);
    if (sqlca.sqlcode < 0) { fprintf(stderr, "lg_reversepair_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; }

    strncpy(rec.biz_date, bizdate, sizeof(rec.biz_date)-1); rec.biz_date[sizeof(rec.biz_date)-1] = 0;
    rec.reversed_posts = h_cnt;
    printf(">>> lg_reversepair_batch COMMIT: date=%s reversed_posts=%ld\n", rec.biz_date, rec.reversed_posts);

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