/* @tier medium @module au @transform authorization-online */
/*
 * au_ol_0030.pgc - 카드 최근승인 이력조회(커서 상위 N) (AU_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 "au_core.h"

EXEC SQL INCLUDE sqlca;

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

    char card[20], field[16];
    int  n = 0;

    tx_log(TX_LOG_INFO, "[AU_OL_0030] 카드 최근승인 이력조회 진입");
    if (tx_buf_get(ctx->in, "CARDNO", card, sizeof(card)) != TX_OK) {
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }
    strncpy(h_card, card, 19); h_card[19] = '\0';

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

    tx_buf_reset(ctx->out);
    for (;;) {
        EXEC SQL FETCH cur_recent 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);
        n++;
    }
    EXEC SQL CLOSE cur_recent;

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