/* @tier medium @module py @transform payment-online */
/*
 * py_ol_0030.pgc - 지급 최근이력 조회(가맹점 최근 지급 N건) (PY_OL_0030)  [tier=medium]
 *
 * TxCore TX_SERVICE 엔트리. 요청 TXBUF 를 검증하고 임베디드 SQL / 표준
 * DBIO / tx_call 로 처리한 뒤 응답 TXBUF 를 구성한다.
 */
#include <stdio.h>
#include <string.h>

#include "txcore.h"
#include "txcore_dbio.h"
#include "acq_util.h"
#include "py_core.h"

EXEC SQL INCLUDE sqlca;

TX_SERVICE(PY_OL_0030, ctx)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_merch[16];
    char h_key[16], h_status[2];
    long h_amount;
    EXEC SQL END DECLARE SECTION;

    char merch[16], field[16];
    int  n = 0;
    long total = 0;

    tx_log(TX_LOG_INFO, "[PY_OL_0030] 지급 최근이력 조회 진입");
    if (tx_buf_get(ctx->in, "MERCHID", merch, sizeof(merch)) != TX_OK) {
        tx_return(ctx, TX_EINVAL, ctx->out); return;
    }
    strncpy(h_merch, merch, 15); h_merch[15] = '\0';

    EXEC SQL DECLARE cur_pyhist CURSOR FOR
        SELECT key, amount, status FROM py_ledger
        WHERE merch_id = :h_merch
        ORDER BY reg_ts DESC LIMIT 5;
    EXEC SQL OPEN cur_pyhist;
    if (sqlca.sqlcode != TX_SQL_OK) { TX_DBIO_LOG_ERR("OPEN cur_pyhist"); tx_return(ctx, TX_EDB, ctx->out); return; }

    tx_buf_reset(ctx->out);
    for (;;) {
        EXEC SQL FETCH cur_pyhist INTO :h_key, :h_amount, :h_status;
        if (sqlca.sqlcode == TX_SQL_NOTFOUND) break;
        if (sqlca.sqlcode != TX_SQL_OK) break;
        snprintf(field, sizeof(field), "KEY%d", n);
        tx_buf_sets(ctx->out, field, h_key);
        snprintf(field, sizeof(field), "AMT%d", n);
        tx_buf_setlong(ctx->out, field, h_amount);
        total += h_amount;
        n++;
    }
    EXEC SQL CLOSE cur_pyhist;

    tx_buf_setlong(ctx->out, "COUNT", n);
    tx_buf_setlong(ctx->out, "TOTAL", total);
    tx_log(TX_LOG_INFO, "[PY_OL_0030] 최근이력 merch=%s cnt=%d", merch, n);
    tx_return(ctx, (n > 0) ? TX_OK : TX_ENOENT, ctx->out);
}
