/*
 * rc_amtcase_dbio.pgc - rc 금액 구간 분류 (rc_amtcase_dbio), librcdbio.a.
 * ECPG; 호출자 XA 브랜치에서 수행. CASE 식으로 소/중/대 버킷을 만들어 GROUP BY 로 집계.
 */
#include <string.h>
#include <userlog.h>
#include "rc_amtcase_dbio.h"

long rcdb_amount_buckets(const char *bizdate, long *large_out)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_bucket[8];
    long h_cnt, buckets = 0, large = 0;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL DECLARE acc CURSOR FOR
        SELECT CASE WHEN amount < 10000 THEN 'S'
                    WHEN amount < 1000000 THEN 'M' ELSE 'L' END AS bkt, count(*)
        FROM rc_match_log WHERE biz_date = :h_bizdate GROUP BY bkt;
    EXEC SQL OPEN acc;
    if (sqlca.sqlcode < 0) return -1;
    for (;;) {
        EXEC SQL FETCH acc INTO :h_bucket, :h_cnt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE acc; return -1; }
        buckets++;
        if (h_bucket[0] == 'L') large += h_cnt;
    }
    EXEC SQL CLOSE acc;
    if (large_out) *large_out = large;
    return buckets;
}
