/*
 * ac_feeadj_repeat_dbio.pgc - ac 모듈 DB 접근 함수 세트 (ac_feeadj_repeat_dbio), archived into libacdbio.a.
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 * Shape: GROUP BY purchase_id HAVING count(*) > 1 커서로 반복조정 매입 수 + delta 합.
 */
#include <string.h>
#include <userlog.h>
#include "ac_feeadj_repeat_dbio.h"

/* 수수료조정이 2회 이상 발생한 매입 수를 세고, delta 총합을 delta_out 에 반환. */
long acdb_feeadj_repeat_purchases(const char *bizdate, long *delta_out)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_pid, h_cnt, h_delta, purchases = 0, delta_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 frc CURSOR FOR
        SELECT purchase_id, count(*), coalesce(sum(delta),0) FROM ac_fee_adj
        WHERE biz_date = :h_bizdate
        GROUP BY purchase_id HAVING count(*) > 1;
    EXEC SQL OPEN frc;
    if (sqlca.sqlcode < 0) return -1;
    for (;;) {
        EXEC SQL FETCH frc INTO :h_pid, :h_cnt, :h_delta;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE frc; return -1; }
        purchases++;
        delta_total += h_delta;
    }
    EXEC SQL CLOSE frc;
    *delta_out = delta_total;
    return purchases;
}
