/*
 * ac_cancel_query_dbio.pgc - ac 모듈 DB 접근 함수 세트 (ac_cancel_query_dbio), archived into libacdbio.a.
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 */
#include <string.h>
#include <userlog.h>
#include "ac_cancel_query_dbio.h"

/* 취소유형(FULL/PARTIAL/REFUND/VOID)별 합계를 커서로 누적하여 총 취소금액 반환. */
long acdb_cancel_typed_sum(const char *bizdate)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_type[16];
    long h_amt, total = 0;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL DECLARE cxc CURSOR FOR
        SELECT cancel_type, coalesce(sum(amount),0) FROM ac_cancel
        WHERE biz_date = :h_bizdate GROUP BY cancel_type;
    EXEC SQL OPEN cxc;
    if (sqlca.sqlcode < 0) { userlog("acdb_cancel_typed_sum OPEN [%d]", sqlca.sqlcode); return -1; }
    for (;;) {
        EXEC SQL FETCH cxc INTO :h_type, :h_amt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE cxc; return -1; }
        total += h_amt;
    }
    EXEC SQL CLOSE cxc;
    return total;
}

/* 취소율(bps) = 취소건수 * 10000 / 매입건수 (두 카운트 비교). */
long acdb_cancel_ratio_bps(const char *bizdate)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_canc = 0, h_purc = 0;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL SELECT count(*) INTO :h_canc FROM ac_cancel WHERE biz_date = :h_bizdate;
    if (sqlca.sqlcode < 0) return -1;
    EXEC SQL SELECT count(*) INTO :h_purc FROM purchase WHERE biz_date = :h_bizdate;
    if (sqlca.sqlcode < 0) return -1;
    if (h_purc <= 0) return 0;
    return h_canc * 10000 / h_purc;
}
