/*
 * st_merchhaving_dbio.pgc - st 모듈 DB 접근 함수 세트 (st_merchhaving_dbio), archived into libstdbio.a.
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 * HAVING 커서 - 임계 net 이상 가맹점 수.
 */
#include <string.h>
#include <userlog.h>
#include "st_merchhaving_dbio.h"

long stdb_big_merchants(const char *bizdate, long threshold)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_merch[64];
    long h_thr = threshold, h_net, cnt = 0;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL DECLARE mhc CURSOR FOR
        SELECT merchant_id, coalesce(sum(net),0) FROM settlement
        WHERE biz_date = :h_bizdate GROUP BY merchant_id HAVING coalesce(sum(net),0) >= :h_thr;
    EXEC SQL OPEN mhc;
    if (sqlca.sqlcode < 0) return -1;
    for (;;) {
        EXEC SQL FETCH mhc INTO :h_merch, :h_net;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE mhc; return -1; }
        cnt++;
    }
    EXEC SQL CLOSE mhc;
    return cnt;
}
