/*
 * lg_acct_walk_dbio.pgc - lg 모듈 DB 접근 함수 (lg_acct_walk_dbio), archived into liblgdbio.a.
 * 당일 계정과목 커서 순회 - 불균형 계정 수 누적.
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 */
#include <string.h>
#include <userlog.h>
#include "lg_acct_walk_dbio.h"

/* 커서로 계정별 차/대를 훑어 불균형 계정 수를 누적 반환. */
long lgqdb_acct_walk(const char *bizdate)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_acct[32];
    long h_dr, h_cr;
    EXEC SQL END DECLARE SECTION;
    long bad = 0;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL DECLARE lgw 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;
    EXEC SQL OPEN lgw;
    if (sqlca.sqlcode < 0) return -1;
    for (;;) {
        EXEC SQL FETCH lgw INTO :h_acct, :h_dr, :h_cr;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE lgw; return -1; }
        if (h_dr != h_cr) bad++;
    }
    EXEC SQL CLOSE lgw;
    return bad;
}
