/*
 * mm_issuer_corr_dbio.pgc - mm 모듈 DB 접근 함수 (mm_issuer_corr_dbio), archived into libmmdbio.a.
 * 발급사별 BIN 수 상관 서브쿼리 순회 최대치 (correlated subquery + cursor).
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 */
#include <string.h>
#include <userlog.h>
#include "mm_issuer_corr_dbio.h"

/* 각 발급사의 활성 BIN 수를 상관 서브쿼리로 뽑아 커서로 훑어 최대값 반환. */
long mmdb_issuer_corr_max_bin(void)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_issuer[16];
    long h_bins;
    EXEC SQL END DECLARE SECTION;
    long peak = 0;
    EXEC SQL DECLARE mic CURSOR FOR
        SELECT i.issuer_cd,
               (SELECT count(*) FROM mm_bin b WHERE b.issuer_cd = i.issuer_cd AND b.status = 'ACTIVE')
        FROM mm_issuer i WHERE i.status = 'ACTIVE'
        ORDER BY i.issuer_cd;
    EXEC SQL OPEN mic;
    if (sqlca.sqlcode < 0) return -1;
    for (;;) {
        EXEC SQL FETCH mic INTO :h_issuer, :h_bins;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE mic; return -1; }
        if (h_bins > peak) peak = h_bins;
    }
    EXEC SQL CLOSE mic;
    return peak;
}
