/*
 * lg_merch_walk_dbio.pgc - lg 모듈 DB 접근 함수 (lg_merch_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_merch_walk_dbio.h"

/* 가맹점 라인을 커서로 훑어 순액(차변-대변) 누적. */
long lgqdb_merch_walk(const char *merch, const char *bizdate)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_merch[64], h_bizdate[16], h_dc[4];
    long h_amt;
    EXEC SQL END DECLARE SECTION;
    long net = 0;
    strncpy(h_merch, merch, sizeof(h_merch)-1); h_merch[sizeof(h_merch)-1] = 0;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL DECLARE lmw CURSOR FOR
        SELECT dc, amount FROM lg_ledger_line
        WHERE merchant_id = :h_merch AND biz_date = :h_bizdate;
    EXEC SQL OPEN lmw;
    if (sqlca.sqlcode < 0) return -1;
    for (;;) {
        EXEC SQL FETCH lmw INTO :h_dc, :h_amt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE lmw; return -1; }
        net += (h_dc[0] == 'D') ? h_amt : -h_amt;
    }
    EXEC SQL CLOSE lmw;
    return net;
}
