/*
 * au_summary_weightavg_dbio.pgc - au 모듈 DB 접근 함수 세트 (au_summary_weightavg_dbio), archived into libaudbio.a.
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 * Shape: 커서로 가맹점별 행을 순회하며 건수 가중 평균 티켓을 C 측에서 누산/산출.
 */
#include <string.h>
#include <userlog.h>
#include "au_summary_weightavg_dbio.h"

/* 건수(auth_count)를 가중치로 하는 평균 승인 티켓을 커서 누산으로 계산. */
long audb_summary_weighted_ticket(const char *bizdate)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_merch[64];
    long h_cnt, h_amt;
    EXEC SQL END DECLARE SECTION;
    long num = 0, den = 0;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL DECLARE swc CURSOR FOR
        SELECT merchant_id, auth_count, auth_amount FROM au_summary WHERE biz_date = :h_bizdate;
    EXEC SQL OPEN swc;
    if (sqlca.sqlcode < 0) return -1;
    for (;;) {
        EXEC SQL FETCH swc INTO :h_merch, :h_cnt, :h_amt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE swc; return -1; }
        num += h_amt;
        den += h_cnt;
    }
    EXEC SQL CLOSE swc;
    if (den <= 0) return 0;
    return num / den;
}
