/*
 * au_merchant_active_dbio.pgc - au 모듈 DB 접근 함수 세트 (au_merchant_active_dbio), archived into libaudbio.a.
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 * Shape: GROUP BY merchant_id HAVING count(*) >= 최소건수, 커서로 활성 가맹점 계수.
 */
#include <string.h>
#include <userlog.h>
#include "au_merchant_active_dbio.h"

/* 당일 승인 건수가 min_auths 이상인 가맹점 수. */
long audb_active_merchant_count(const char *bizdate, long min_auths)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_merch[64];
    long h_cnt, h_min = min_auths, active = 0;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL DECLARE amc CURSOR FOR
        SELECT merchant_id, count(*) FROM au_authorization
        WHERE biz_date = :h_bizdate
        GROUP BY merchant_id HAVING count(*) >= :h_min;
    EXEC SQL OPEN amc;
    if (sqlca.sqlcode < 0) return -1;
    for (;;) {
        EXEC SQL FETCH amc INTO :h_merch, :h_cnt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE amc; return -1; }
        active++;
    }
    EXEC SQL CLOSE amc;
    return active;
}
