/*
 * lg_balproof_batch.pgc - lg 잔액 증명 배치 (커서 + XA).
 *
 * 당일 계정잔액(lg_account_bal) 각 행을 원장 라인 재집계와 대조하고,
 * 불일치 계정은 dbio 재계산(lgdb_recalc_acct_bal)으로 즉시 보정한다.
 * 검증/불일치/보정 건수를 보고. 모두 ONE global XA transaction 에서 수행.
 * Usage: lg_balproof_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "lg_dbio.h"
#include "lg_balproof_batch.h"

int main(int argc, char **argv)
{
    lg_balproof_rec_t rec;

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_acct[32];
    long h_bal, h_real;
    EXEC SQL END DECLARE SECTION;

    memset(&rec, 0, sizeof(rec));
    strncpy(rec.biz_date, (argc > 1) ? argv[1] : "2026-07-19", sizeof(rec.biz_date)-1);
    strncpy(h_bizdate, rec.biz_date, 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 bp_cur CURSOR FOR
        SELECT a.acct, a.balance,
               coalesce((SELECT sum(CASE WHEN l.dc = 'D' THEN l.amount ELSE -l.amount END)
                         FROM lg_ledger_line l
                         WHERE l.acct = a.acct AND l.biz_date = a.biz_date), 0)
        FROM lg_account_bal a WHERE a.biz_date = :h_bizdate
        ORDER BY a.acct;
    EXEC SQL OPEN bp_cur;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH bp_cur INTO :h_acct, :h_bal, :h_real;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d]\n", sqlca.sqlcode); EXEC SQL CLOSE bp_cur; tpabort(0); return 1; }
        rec.verified++;
        if (h_bal != h_real) {
            printf("    불일치: %s 기록 %ld vs 재계산 %ld -> 보정\n", h_acct, h_bal, h_real);
            rec.mismatched++;
            if (lgdb_recalc_acct_bal(h_acct, rec.biz_date) < 0) { EXEC SQL CLOSE bp_cur; tpabort(0); return 1; }
            rec.repaired++;
        }
    }
    EXEC SQL CLOSE bp_cur;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> lg_balproof_batch COMMIT: %s 검증 %ld 불일치 %ld 보정 %ld\n",
           rec.biz_date, rec.verified, rec.mismatched, rec.repaired);

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