/*
 * rc_match_batch.pgc - rc 3-way 대사 배치 (커서 + XA).
 *
 * ATMI client: tpinit/tpopen 로 ECPG XA RM 를 열고, tpbegin 으로 ONE global tx
 * 를 시작한 뒤, 승인(approval)과 원장(ledger)이 모두 존재하는 당일 매입을 커서로
 * 순회하며 rc_match_log 에 3WAY MATCHED 를 (dbio 로) 기록하고, 나머지는 EXCEPTION
 * 으로 남긴다. 마지막에 tpcommit 이 XA 2PC 를 구동. 사용법: rc_match_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "rc_dbio.h"

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

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_pid, h_net, h_appr, h_led;
    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 DECLARE rmc CURSOR FOR
        SELECT p.purchase_id, p.net,
               (SELECT count(*) FROM approval a WHERE a.purchase_id = p.purchase_id),
               (SELECT count(*) FROM ledger l WHERE l.purchase_id = p.purchase_id)
        FROM purchase p
        WHERE p.biz_date = :h_bizdate
        ORDER BY p.purchase_id;
    EXEC SQL OPEN rmc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH rmc INTO :h_pid, :h_net, :h_appr, :h_led;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE rmc; tpabort(0); return 1; }
        if (h_appr > 0 && h_led > 0) {
            if (rcdb_insert_match(h_pid, "3WAY", h_net, "MATCHED", bizdate) < 0) {
                EXEC SQL CLOSE rmc; tpabort(0); return 1;
            }
            rows++;
        } else {
            if (rcdb_insert_match(h_pid, "3WAY", h_net, "EXCEPTION", bizdate) < 0) {
                EXEC SQL CLOSE rmc; tpabort(0); return 1;
            }
            exc++;
        }
    }
    EXEC SQL CLOSE rmc;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> rc_match_batch COMMIT: bizdate=%s matched=%ld exception=%ld\n", bizdate, rows, exc);

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