/*
 * lg_imbalscan_batch.pgc - lg 계정 대차 불균형 스캔 (커서 배치, XA).
 *
 * Walks an account-grouped cursor summing debit/credit per account and counts
 * how many accounts are out of balance, inside ONE XA transaction.
 * Usage: lg_imbalscan_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "lg_imbalscan_batch.h"

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

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

    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    rec.accts = 0; rec.imbalanced = 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 iscur CURSOR FOR
        SELECT acct, coalesce(sum(amount) FILTER (WHERE dc = 'D'),0),
                     coalesce(sum(amount) FILTER (WHERE dc = 'C'),0)
        FROM lg_ledger_line WHERE biz_date = :h_bizdate GROUP BY acct ORDER BY acct;
    EXEC SQL OPEN iscur;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "lg_imbalscan_batch OPEN FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH iscur INTO :h_acct, :h_dr, :h_cr;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE iscur; fprintf(stderr, "lg_imbalscan_batch FETCH FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }
        rec.accts++;
        if (h_dr != h_cr) rec.imbalanced++;
    }
    EXEC SQL CLOSE iscur;

    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;
    printf(">>> lg_imbalscan_batch COMMIT: date=%s accts=%ld imbalanced=%ld\n",
           rec.biz_date, rec.accts, rec.imbalanced);

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