/* @tier medium @module au @transform authorization-online */
/*
 * au_ol_0020.pgc - 승인번호 채번(당일 순번 생성) (AU_OL_0020)  [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_0020, ctx)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bdate[9];
    int  h_seq;
    EXEC SQL END DECLARE SECTION;

    char bdate[16], approval[16];

    tx_log(TX_LOG_INFO, "[AU_OL_0020] 승인번호 채번 진입");
    if (tx_buf_get(ctx->in, "BIZDATE", bdate, sizeof(bdate)) != TX_OK)
        date_today(bdate);
    strncpy(h_bdate, bdate, 8); h_bdate[8] = '\0';

    EXEC SQL SELECT count(*) + 1 INTO :h_seq
        FROM au_ledger WHERE biz_date = :h_bdate;
    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("au_ol_0020 채번");
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }

    snprintf(approval, sizeof(approval), "%.8s%06d", bdate, h_seq);
    tx_buf_reset(ctx->out);
    tx_buf_sets(ctx->out, "APPROVALNO", approval);
    tx_buf_setlong(ctx->out, "SEQ", h_seq);
    tx_log(TX_LOG_INFO, "[AU_OL_0020] 승인번호 채번 %s (seq=%d)", approval, h_seq);
    tx_return(ctx, TX_OK, ctx->out);
}
