/*
 * au_summary_riskmerch_dbio.pgc - au 모듈 DB 접근 함수 세트 (au_summary_riskmerch_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 sum(decline_count) > sum(approve_count) 커서 계수.
 */
#include <string.h>
#include <userlog.h>
#include "au_summary_riskmerch_dbio.h"

/* 거절 건수가 승인 건수보다 많은(위험) 가맹점 수를 GROUP BY/HAVING 커서로 계수. */
long audb_decline_heavy_merchants(const char *bizdate)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_merch[64];
    long h_dec, h_app, risky = 0;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL DECLARE rmc CURSOR FOR
        SELECT merchant_id, sum(decline_count), sum(approve_count) FROM au_summary
        WHERE biz_date = :h_bizdate
        GROUP BY merchant_id HAVING sum(decline_count) > sum(approve_count);
    EXEC SQL OPEN rmc;
    if (sqlca.sqlcode < 0) return -1;
    for (;;) {
        EXEC SQL FETCH rmc INTO :h_merch, :h_dec, :h_app;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE rmc; return -1; }
        risky++;
    }
    EXEC SQL CLOSE rmc;
    return risky;
}
