/*
 * lg_trialbal_batch.pgc - lg 시산표(trial balance) 배치 (커서 + XA).
 *
 * 당일 원장 라인을 계정과목(acct)별로 GROUP BY 하여 차변/대변 합계를 산출하고
 * lg_trial_bal 에 upsert 한다. 전체 대차 차액(diff) 을 누적해 마지막에 출력하여
 * 복식부기 균형 여부를 검증한다. 모두 ONE global XA transaction 하에서 수행.
 * Usage: lg_trialbal_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "lg_dbio.h"

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

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_acct[32];
    long h_dr, h_cr, h_diff;
    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 ltc CURSOR FOR
        SELECT acct,
               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 ltc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH ltc INTO :h_acct, :h_dr, :h_cr;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE ltc; tpabort(0); return 1; }
        h_diff = h_dr - h_cr;

        EXEC SQL INSERT INTO lg_trial_bal (acct, biz_date, debit_total, credit_total, diff)
            VALUES (:h_acct, :h_bizdate, :h_dr, :h_cr, :h_diff)
            ON CONFLICT (acct, biz_date) DO UPDATE
            SET debit_total = EXCLUDED.debit_total, credit_total = EXCLUDED.credit_total,
                diff = EXCLUDED.diff, updated_at = now();
        if (sqlca.sqlcode < 0) { fprintf(stderr, "UPSERT FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE ltc; tpabort(0); return 1; }
        net_diff += h_diff;
        rows++;
    }
    EXEC SQL CLOSE ltc;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> lg_trialbal_batch COMMIT: bizdate=%s 계정=%ld 총대차차액=%ld %s\n",
           bizdate, rows, net_diff, (net_diff == 0) ? "(균형)" : "(불균형!)");

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