/*
 * lg_statacct_batch.pgc - lg 계정별 원장 통계 배치 (커서 + XA).
 *
 * 당일 원장을 계정과목별로 훑어 라인 수/차변/대변/잔액/평균 분개금액을
 * 리포트하고, 마지막에 전 계정 합계로 총차변=총대변(복식부기 균형)을
 * 검산한다. 조회 전용 통계. ONE global XA transaction 에서 수행.
 * Usage: lg_statacct_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "lg_dbio.h"
#include "lg_statacct_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    lg_statacct_line_t rec;
    long accts = 0, grand_dr = 0, grand_cr = 0;

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_acct[32];
    long h_lines, h_dr, h_cr;
    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 sab_cur CURSOR FOR
        SELECT acct, count(*),
               coalesce(sum(CASE WHEN dc = 'D' THEN amount ELSE 0 END), 0),
               coalesce(sum(CASE WHEN dc = 'C' THEN amount ELSE 0 END), 0)
        FROM lg_ledger_line WHERE biz_date = :h_bizdate
        GROUP BY acct ORDER BY acct;
    EXEC SQL OPEN sab_cur;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    printf("--- 계정별 원장 통계 (%s) ---\n", bizdate);
    for (;;) {
        EXEC SQL FETCH sab_cur INTO :h_acct, :h_lines, :h_dr, :h_cr;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d]\n", sqlca.sqlcode); EXEC SQL CLOSE sab_cur; tpabort(0); return 1; }
        memset(&rec, 0, sizeof(rec));
        strncpy(rec.acct, h_acct, sizeof(rec.acct)-1);
        rec.lines = h_lines; rec.debit = h_dr; rec.credit = h_cr;
        rec.balance = h_dr - h_cr;
        rec.avg_line = (h_lines > 0) ? (h_dr + h_cr) / h_lines : 0;
        printf("    %-14s %5ld라인 차 %12ld 대 %12ld 잔액 %12ld 평균 %10ld\n",
               rec.acct, rec.lines, rec.debit, rec.credit, rec.balance, rec.avg_line);
        grand_dr += h_dr; grand_cr += h_cr;
        accts++;
    }
    EXEC SQL CLOSE sab_cur;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> lg_statacct_batch COMMIT: %ld계정 총차변 %ld 총대변 %ld %s\n",
           accts, grand_dr, grand_cr, (grand_dr == grand_cr) ? "(균형)" : "(불균형!)");

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