/*
 * ac_cancel_casebucket_dbio.pgc - ac 모듈 DB 접근 함수 세트 (ac_cancel_casebucket_dbio), archived into libacdbio.a.
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 * Shape: CASE WHEN 금액 구간별 건수를 한 번의 집계로 산출.
 */
#include <string.h>
#include <userlog.h>
#include "ac_cancel_casebucket_dbio.h"

/* 취소 금액을 소액(<1만)/중액(<10만)/고액 3구간으로 CASE 버킷팅하여 out 에 채움. */
int acdb_cancel_buckets(const char *bizdate, ac_cancel_bucket_rec_t *out)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_sm = 0, h_md = 0, h_lg = 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(*) FILTER (WHERE amount < 10000),
        count(*) FILTER (WHERE amount >= 10000 AND amount < 100000),
        count(*) FILTER (WHERE amount >= 100000)
        INTO :h_sm, :h_md, :h_lg
        FROM ac_cancel WHERE biz_date = :h_bizdate;
    if (sqlca.sqlcode < 0) {
        userlog("acdb_cancel_buckets FAIL [%d] %s", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc);
        return -1;
    }
    out->small = h_sm;
    out->mid = h_md;
    out->large = h_lg;
    return 0;
}
