/*
 * au_preauth_agg_dbio.pgc - au 모듈 DB 접근 함수 세트 (au_preauth_agg_dbio), archived into libaudbio.a.
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 * Shape: GROUP BY ... HAVING via cursor (미확정 예비승인 보유 가맹점 수).
 */
#include <string.h>
#include <userlog.h>
#include "au_preauth_agg_dbio.h"

/* 미확정(P) 예비승인을 1건 이상 보유한 가맹점 수를 GROUP BY/HAVING 커서로 계수. */
long audb_preauth_open_merchants(const char *bizdate)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_merch[64];
    long h_cnt, merchants = 0;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL DECLARE pamc CURSOR FOR
        SELECT merchant_id, count(*) FROM au_preauth
        WHERE biz_date = :h_bizdate AND status = 'P'
        GROUP BY merchant_id HAVING count(*) >= 1;
    EXEC SQL OPEN pamc;
    if (sqlca.sqlcode < 0) return -1;
    for (;;) {
        EXEC SQL FETCH pamc INTO :h_merch, :h_cnt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE pamc; return -1; }
        merchants++;
    }
    EXEC SQL CLOSE pamc;
    return merchants;
}
