/* Processed by ecpg (15.18 (Debian 15.18-0+deb12u1)) */
/* These include files are added by the preprocessor */
#include <ecpglib.h>
#include <ecpgerrno.h>
#include <sqlca.h>
/* End of automatic include section */

#line 1 "app/online/rc_ol_0021.pgc"
/* @tier easy @module rc @transform reconciliation-online */
/*
 * rc_ol_0021.pgc - 대사 diff 리포트 조회 온라인 서비스 (RC_OL_0021)
 *
 * 원장 1건을 읽어 승인계에서 넘어온 값과의 차이를 리포트한다.
 *
 * [입력]
 *   KEY     - 처리키(승인/거래 번호)
 *   APPRAMT - 승인금액(원)
 *   EXPFEE  - 예상 수수료(원)
 *
 * [산출]
 *   AMTDIFF = amount - APPRAMT   (금액 차이)
 *   FEEDIFF = fee    - EXPFEE    (수수료 차이)
 *   RESULT  = "OK"   (두 차이가 모두 0)
 *           = "DIFF" (하나라도 0 이 아님)
 *
 * 이 서비스는 대사 불일치 원인 분석용 리포트이며, 원장 상태를 전혀
 * 변경하지 않는 순수 조회(read-only) 서비스이다. 커서를 사용하지 않는다.
 */
#include <stdio.h>
#include <string.h>

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


#line 1 "/usr/include/postgresql/sqlca.h"
#ifndef POSTGRES_SQLCA_H
#define POSTGRES_SQLCA_H

#ifndef PGDLLIMPORT
#if  defined(WIN32) || defined(__CYGWIN__)
#define PGDLLIMPORT __declspec (dllimport)
#else
#define PGDLLIMPORT
#endif							/* __CYGWIN__ */
#endif							/* PGDLLIMPORT */

#define SQLERRMC_LEN	150

#ifdef __cplusplus
extern "C"
{
#endif

struct sqlca_t
{
	char		sqlcaid[8];
	long		sqlabc;
	long		sqlcode;
	struct
	{
		int			sqlerrml;
		char		sqlerrmc[SQLERRMC_LEN];
	}			sqlerrm;
	char		sqlerrp[8];
	long		sqlerrd[6];
	/* Element 0: empty						*/
	/* 1: OID of processed tuple if applicable			*/
	/* 2: number of rows processed				*/
	/* after an INSERT, UPDATE or				*/
	/* DELETE statement					*/
	/* 3: empty						*/
	/* 4: empty						*/
	/* 5: empty						*/
	char		sqlwarn[8];
	/* Element 0: set to 'W' if at least one other is 'W'	*/
	/* 1: if 'W' at least one character string		*/
	/* value was truncated when it was			*/
	/* stored into a host variable.             */

	/*
	 * 2: if 'W' a (hopefully) non-fatal notice occurred
	 */	/* 3: empty */
	/* 4: empty						*/
	/* 5: empty						*/
	/* 6: empty						*/
	/* 7: empty						*/

	char		sqlstate[5];
};

struct sqlca_t *ECPGget_sqlca(void);

#ifndef POSTGRES_ECPG_INTERNAL
#define sqlca (*ECPGget_sqlca())
#endif

#ifdef __cplusplus
}
#endif

#endif

#line 28 "app/online/rc_ol_0021.pgc"


TX_SERVICE(RC_OL_0021, ctx)
{
    rc_rec_t rec;
    char key[16];
    long appr_amt = 0;
    long exp_fee  = 0;
    long amt_diff, fee_diff;
    int  rc;
    const char *result;

    tx_log(TX_LOG_INFO, "[RC_OL_0021] 대사 diff 리포트 조회 서비스 진입");

    if (tx_buf_get(ctx->in, "KEY", key, sizeof(key)) != TX_OK) {
        tx_log(TX_LOG_ERROR, "[RC_OL_0021] KEY 누락");
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }
    if (tx_buf_getlong(ctx->in, "APPRAMT", &appr_amt) != TX_OK) {
        tx_log(TX_LOG_ERROR, "[RC_OL_0021] APPRAMT(승인금액) 누락");
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }
    if (tx_buf_getlong(ctx->in, "EXPFEE", &exp_fee) != TX_OK) {
        tx_log(TX_LOG_ERROR, "[RC_OL_0021] EXPFEE(예상 수수료) 누락");
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

    /* 승인금액/예상수수료는 음수가 될 수 없다 */
    if (appr_amt < 0 || exp_fee < 0) {
        tx_log(TX_LOG_WARN,
               "[RC_OL_0021] 입력값 음수 오류 key=%s appramt=%ld expfee=%ld",
               key, appr_amt, exp_fee);
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

    tx_log(TX_LOG_INFO,
           "[RC_OL_0021] 대사 diff 입력 key=%s 승인금액=%ld 예상수수료=%ld",
           key, appr_amt, exp_fee);

    memset(&rec, 0, sizeof(rec));
    rc = rc_rec_select(key, &rec);
    if (rc != TX_OK) {
        tx_log(TX_LOG_WARN, "[RC_OL_0021] 원장 조회 실패 key=%s rc=%d(%s)",
               key, rc, tx_strerror(rc));
        tx_return(ctx, rc, ctx->out);
        return;
    }

    tx_log(TX_LOG_INFO,
           "[RC_OL_0021] 대상 조회 key=%s 매입액=%ld 수수료=%ld 상태=%s",
           key, rec.amount, rec.fee, rec.status);

    /* 차이 산출 (원장 무변경) */
    amt_diff = rec.amount - appr_amt;
    fee_diff = rec.fee - exp_fee;

    if (amt_diff == 0 && fee_diff == 0) {
        result = "OK";
        tx_log(TX_LOG_INFO, "[RC_OL_0021] 차이없음 key=%s", key);
    } else {
        result = "DIFF";
        /* 차이 유형 세분화 로그: 금액/수수료 어느 항목이 어긋났는지 기록 */
        if (amt_diff != 0 && fee_diff != 0)
            tx_log(TX_LOG_WARN,
                   "[RC_OL_0021] 금액+수수료 동시 불일치 key=%s 금액차=%ld 수수료차=%ld",
                   key, amt_diff, fee_diff);
        else if (amt_diff != 0)
            tx_log(TX_LOG_WARN,
                   "[RC_OL_0021] 금액 불일치 key=%s 금액차=%ld", key, amt_diff);
        else
            tx_log(TX_LOG_WARN,
                   "[RC_OL_0021] 수수료 불일치 key=%s 수수료차=%ld", key, fee_diff);
    }

    tx_buf_reset(ctx->out);
    tx_buf_sets(ctx->out, "KEY", rec.key);
    tx_buf_setlong(ctx->out, "AMOUNT", rec.amount);
    tx_buf_setlong(ctx->out, "APPRAMT", appr_amt);
    tx_buf_setlong(ctx->out, "AMTDIFF", amt_diff);
    tx_buf_setlong(ctx->out, "FEE", rec.fee);
    tx_buf_setlong(ctx->out, "EXPFEE", exp_fee);
    tx_buf_setlong(ctx->out, "FEEDIFF", fee_diff);
    tx_buf_sets(ctx->out, "RESULT", result);

    tx_log(TX_LOG_INFO,
           "[RC_OL_0021] 리포트완료 key=%s 결과=%s 금액차=%ld 수수료차=%ld",
           key, result, amt_diff, fee_diff);
    tx_return(ctx, TX_OK, ctx->out);
}
