/*
 * lg_type_walk_dbio.pgc - lg 모듈 DB 접근 함수 (lg_type_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_type_walk_dbio.h"

/* 커서 순회: 전표 유형별 (건수, 합계) 를 훑어 floor_amt 이상 유형 수 반환. */
long lgqdb_type_walk_heavy(const char *bizdate, long floor_amt)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_type[16];
    long h_floor = floor_amt, h_cnt, h_sum;
    EXEC SQL END DECLARE SECTION;
    long heavy = 0;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL DECLARE lgtw CURSOR FOR
        SELECT v.voucher_type, count(l.line_id), coalesce(sum(l.amount),0)
        FROM lg_voucher v JOIN lg_ledger_line l ON l.voucher_id = v.voucher_id
        WHERE v.biz_date = :h_bizdate GROUP BY v.voucher_type ORDER BY v.voucher_type;
    EXEC SQL OPEN lgtw;
    if (sqlca.sqlcode < 0) return -1;
    for (;;) {
        EXEC SQL FETCH lgtw INTO :h_type, :h_cnt, :h_sum;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE lgtw; return -1; }
        if (h_sum >= h_floor) heavy++;
    }
    EXEC SQL CLOSE lgtw;
    return heavy;
}
