/*
 * st_paycursor2_dbio.pgc - 소액 예정지급 보류 전환 (st_paycursor2_dbio), libstdbio.a.
 * ECPG; FOR UPDATE 커서로 SCHEDULED 지급을 순회하며 최소액 미만이면 WHERE CURRENT OF 로 HELD 전환.
 */
#include <string.h>
#include <userlog.h>
#include "st_paycursor2_dbio.h"

long stdb_hold_small_payments(const char *bizdate, long floor_amt)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_floor = floor_amt, h_id, h_net, held = 0;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL DECLARE p2c CURSOR FOR
        SELECT pay_id, net_amount FROM st_payment
        WHERE biz_date = :h_bizdate AND status = 'SCHEDULED' FOR UPDATE;
    EXEC SQL OPEN p2c;
    if (sqlca.sqlcode < 0) return -1;
    for (;;) {
        EXEC SQL FETCH p2c INTO :h_id, :h_net;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE p2c; return -1; }
        if (h_net < h_floor) {
            EXEC SQL UPDATE st_payment SET status = 'HELD' WHERE CURRENT OF p2c;
            if (sqlca.sqlcode < 0) { EXEC SQL CLOSE p2c; return -1; }
            held++;
        }
    }
    EXEC SQL CLOSE p2c;
    return held;
}
