/* @tier hard @module au @transform authorization-online */
/*
 * au_ol_0010.pgc - 카드유효성 연계 후 승인접수 (AU_OL_0010)  [tier=hard]
 *
 * 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_0010, ctx)
{
    char key[16];
    if (tx_buf_get(ctx->in, "KEY", key, sizeof(key)) != TX_OK) {
        tx_log(TX_LOG_ERROR, "[AU_OL_0010] KEY 누락");
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }
    EXEC SQL BEGIN DECLARE SECTION;
    char h_key[16], h_card[20], h_bdate[9], h_status[2];
    long h_amount;
    EXEC SQL END DECLARE SECTION;

    TXBUF *req;
    char card[20], vresp[8];
    long amount = 0;
    int  rc;

    tx_log(TX_LOG_INFO, "[AU_OL_0010] 카드유효성 연계승인 진입");
    if (tx_buf_get(ctx->in, "CARDNO", card, sizeof(card)) != TX_OK) {
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }
    tx_buf_getlong(ctx->in, "AMOUNT", &amount);

    req = tx_buf_alloc();
    if (!req) { tx_return(ctx, TX_ENOMEM, ctx->out); return; }
    tx_buf_sets(req, "CARDNO", card);
    rc = tx_call("VL_CARD", req, ctx->out);
    tx_buf_free(req);
    if (rc != TX_OK ||
        (tx_buf_get(ctx->out, "RESPCODE", vresp, sizeof(vresp)) == TX_OK &&
         strcmp(vresp, RESP_OK) != 0)) {
        tx_log(TX_LOG_WARN, "[AU_OL_0010] 카드 유효성 실패 card=%s", card);
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_INVALID);
        tx_return(ctx, TX_FAIL, ctx->out);
        return;
    }

    strncpy(h_key, key, 15); h_key[15] = '\0';
    strncpy(h_card, card, 19); h_card[19] = '\0';
    date_today(h_bdate);
    strncpy(h_status, AU_ST_RECV, 1); h_status[1] = '\0';
    h_amount = amount;

    if (tx_begin() != TX_OK) tx_log(TX_LOG_WARN, "[AU_OL_0010] tx_begin 경고");
    EXEC SQL INSERT INTO au_ledger (key, merch_id, card_no, amount, biz_date, status, fee)
        VALUES (:h_key, 'ONLINE', :h_card, :h_amount, :h_bdate, :h_status, 0);
    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("au_ol_0010 접수");
        tx_abort();
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }
    tx_commit();

    tx_buf_reset(ctx->out);
    tx_buf_sets(ctx->out, "RESPCODE", RESP_OK);
    tx_buf_sets(ctx->out, "KEY", key);
    tx_log(TX_LOG_INFO, "[AU_OL_0010] 카드검증+접수 완료 key=%s", key);
    tx_return(ctx, TX_OK, ctx->out);
}
