/* @tier hard @module rc @transform reconciliation-online */
/*
 * rc_ol_0026.pgc - 중복거래 대사 온라인 서비스 (RC_OL_0026)
 *
 * 동일 가맹점(MERCHID)/동일 금액(AMOUNT)/동일 영업일(BIZDATE) 조합의
 * 원장을 커서로 순회하여 중복 여부를 판정한다. 일치 건수(DUPCNT) 를
 * 세고 먼저 조회된 최대 2건의 처리키(KEY0/KEY1) 를 확보한다.
 *   DUPCNT > 1  → "DUPLICATE"
 *   DUPCNT == 1 → "UNIQUE"
 *   DUPCNT == 0 → "NOTFOUND"
 * 원장을 변경하지 않는 읽기전용 서비스이다.
 */
#include <stdio.h>
#include <string.h>

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

EXEC SQL INCLUDE sqlca;

TX_SERVICE(RC_OL_0026, ctx)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_merch_id[16];
    char h_biz_date[9];
    long h_amount;
    char h_key[16];
    EXEC SQL END DECLARE SECTION;

    char merch[16];
    char bizdate[9];
    char sample[2][16];
    long amount = 0;
    long dupcnt = 0;
    int  captured = 0;
    int  i;
    const char *result;

    tx_log(TX_LOG_INFO, "[RC_OL_0026] 중복거래 대사 서비스 진입");

    if (tx_buf_get(ctx->in, "MERCHID", merch, sizeof(merch)) != TX_OK) {
        tx_log(TX_LOG_ERROR, "[RC_OL_0026] MERCHID(가맹점번호) 누락");
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }
    if (tx_buf_getlong(ctx->in, "AMOUNT", &amount) != TX_OK) {
        tx_log(TX_LOG_ERROR, "[RC_OL_0026] AMOUNT(거래금액) 누락");
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }
    if (tx_buf_get(ctx->in, "BIZDATE", bizdate, sizeof(bizdate)) != TX_OK) {
        tx_log(TX_LOG_ERROR, "[RC_OL_0026] BIZDATE(영업일) 누락");
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

    if (!amount_is_valid(amount)) {
        tx_log(TX_LOG_WARN, "[RC_OL_0026] 금액 유효성 오류 amount=%ld", amount);
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }
    if (!date_is_valid(bizdate)) {
        tx_log(TX_LOG_WARN, "[RC_OL_0026] 영업일 형식 오류 date=%s", bizdate);
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

    for (i = 0; i < 2; i++)
        sample[i][0] = '\0';

    strncpy(h_merch_id, merch, sizeof(h_merch_id) - 1);
    h_merch_id[sizeof(h_merch_id) - 1] = '\0';
    strncpy(h_biz_date, bizdate, sizeof(h_biz_date) - 1);
    h_biz_date[sizeof(h_biz_date) - 1] = '\0';
    h_amount = amount;

    /* 가맹점/금액/영업일이 동일한 원장을 처리키 순으로 순회 */
    EXEC SQL DECLARE cur_rc_ol_0026 CURSOR FOR
        SELECT key
        FROM rc_ledger
        WHERE merch_id = :h_merch_id
          AND amount   = :h_amount
          AND biz_date = :h_biz_date
        ORDER BY key;

    EXEC SQL OPEN cur_rc_ol_0026;
    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("OPEN cur_rc_ol_0026");
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }

    for (;;) {
        EXEC SQL FETCH cur_rc_ol_0026 INTO :h_key;

        if (sqlca.sqlcode == TX_SQL_NOTFOUND)
            break;
        if (sqlca.sqlcode != TX_SQL_OK) {
            TX_DBIO_LOG_ERR("FETCH cur_rc_ol_0026");
            EXEC SQL CLOSE cur_rc_ol_0026;
            tx_return(ctx, TX_EDB, ctx->out);
            return;
        }

        dupcnt++;

        if (captured < 2) {
            strncpy(sample[captured], h_key, sizeof(sample[captured]) - 1);
            sample[captured][sizeof(sample[captured]) - 1] = '\0';
            captured++;
        }
    }

    EXEC SQL CLOSE cur_rc_ol_0026;

    /* 중복 판정 */
    if (dupcnt > 1)
        result = "DUPLICATE";
    else if (dupcnt == 1)
        result = "UNIQUE";
    else
        result = "NOTFOUND";

    tx_log(TX_LOG_INFO,
           "[RC_OL_0026] 중복대사 merch=%s amount=%ld date=%s 건수=%ld 결과=%s",
           merch, amount, bizdate, dupcnt, result);

    tx_buf_reset(ctx->out);
    tx_buf_sets(ctx->out, "MERCHID", merch);
    tx_buf_setlong(ctx->out, "AMOUNT", amount);
    tx_buf_sets(ctx->out, "BIZDATE", bizdate);
    tx_buf_setlong(ctx->out, "DUPCNT", dupcnt);
    tx_buf_sets(ctx->out, "RESULT", result);
    tx_buf_sets(ctx->out, "KEY0", sample[0]);
    tx_buf_sets(ctx->out, "KEY1", sample[1]);
    tx_return(ctx, TX_OK, ctx->out);
}
