/*
 * ac_merchant_bigday_dbio.pgc - ac 모듈 DB 접근 함수 세트 (ac_merchant_bigday_dbio), archived into libacdbio.a.
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 * Shape: GROUP BY ... HAVING sum(amount) >= 임계, 커서로 가맹점 계수 + 최대 group 합.
 */
#include <string.h>
#include <userlog.h>
#include "ac_merchant_bigday_dbio.h"

/* 당일 매입합이 threshold 이상인 가맹점 수를 세고, 최대 group 합은 peak 로 보고. */
long acdb_bigday_merchant_count(const char *bizdate, long threshold)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_merch[64];
    long h_gross, h_thr = threshold, cnt = 0, peak = 0;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL DECLARE bdc CURSOR FOR
        SELECT merchant_id, sum(amount) FROM purchase
        WHERE biz_date = :h_bizdate
        GROUP BY merchant_id HAVING sum(amount) >= :h_thr;
    EXEC SQL OPEN bdc;
    if (sqlca.sqlcode < 0) return -1;
    for (;;) {
        EXEC SQL FETCH bdc INTO :h_merch, :h_gross;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE bdc; return -1; }
        cnt++;
        if (h_gross > peak) peak = h_gross;
    }
    EXEC SQL CLOSE bdc;
    if (peak < 0) return -1;
    return cnt;
}
