/*
 * py_channel_walk_dbio.pgc - py 모듈 DB 접근 함수 세트 (py_channel_walk_dbio), archived into libpydbio.a.
 * 채널별 집계를 커서로 순회하며 활성 채널(기준 건수 이상)을 센다.
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 */
#include <string.h>
#include <userlog.h>
#include "py_channel_walk_dbio.h"

/* 커서 순회: 채널별 (건수, 금액) 을 훑어 min_txn 이상인 채널 수 반환. */
long pydb_channel_active(const char *bizdate, long min_txn)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_ch[16];
    long h_min = min_txn, h_cnt, h_amt;
    EXEC SQL END DECLARE SECTION;
    long active = 0;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL DECLARE pych CURSOR FOR
        SELECT channel, count(*), coalesce(sum(amount),0)
        FROM py_payout WHERE biz_date = :h_bizdate GROUP BY channel ORDER BY channel;
    EXEC SQL OPEN pych;
    if (sqlca.sqlcode < 0) return -1;
    for (;;) {
        EXEC SQL FETCH pych INTO :h_ch, :h_cnt, :h_amt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE pych; return -1; }
        if (h_cnt >= h_min) active++;
    }
    EXEC SQL CLOSE pych;
    return active;
}
