/* @tier easy @module cl @transform closing-online */
/*
 * cl_ol_0031.pgc - 마감 온라인 서비스 (CL_OL_0031)  [tier=easy]
 *
 * 마감 스냅샷 비교
 * ----------------------------------------------------------------------
 * 두 스냅샷 처리키(SS1, SS2)를 표준 DBIO(cl_rec_select) 로 각각 조회
 * 하여, 두 스냅샷의 합계금액(amount) 차이와 일치 여부(MATCH=Y/N) 를
 * diff 응답으로 반환한다. 어느 한쪽 스냅샷이 없으면 비교 불가로
 * ENOENT 를 응답한다.
 *
 * 금액 차이에 더해 건수(fee 필드에 적재) 차이와 변동 방향(DIRECTION:
 * UP/DOWN/FLAT), 기준(SS1) 대비 변동률(%)을 산출하여 제공한다.
 * 감사추적을 위해 선택 입력 REQID 를 반영한다.
 */
#include <stdio.h>
#include <string.h>

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

EXEC SQL INCLUDE sqlca;

TX_SERVICE(CL_OL_0031, ctx)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_ss1[16];
    char h_ss2[16];
    long h_diff;
    char h_direction[8];
    char h_reqid[32];
    EXEC SQL END DECLARE SECTION;

    cl_rec_t rec1, rec2;
    char ss1[16], ss2[16];
    char reqid[32];
    char diff_won[32];
    char summary[TX_VAL_LEN];
    const char *direction;
    long diff, cnt_diff, abs_diff;
    long rate;
    long persisted = 0;
    int  rc1, rc2;

    tx_log(TX_LOG_INFO, "[CL_OL_0031] 마감 스냅샷 비교 서비스 진입");

    /* 1) 입력 수신 */
    if (tx_buf_get(ctx->in, "SS1", ss1, sizeof(ss1)) != TX_OK ||
        tx_buf_get(ctx->in, "SS2", ss2, sizeof(ss2)) != TX_OK) {
        tx_log(TX_LOG_ERROR, "[CL_OL_0031] SS1/SS2 누락");
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_INVALID);
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }
    if (tx_buf_get(ctx->in, "REQID", reqid, sizeof(reqid)) != TX_OK)
        strncpy(reqid, "-", sizeof(reqid) - 1);

    /* 2) 두 스냅샷 각각 조회 */
    memset(&rec1, 0, sizeof(rec1));
    memset(&rec2, 0, sizeof(rec2));
    rc1 = cl_rec_select(ss1, &rec1);
    rc2 = cl_rec_select(ss2, &rec2);

    if (rc1 == TX_ENOENT || rc2 == TX_ENOENT) {
        tx_log(TX_LOG_WARN, "[CL_OL_0031] 스냅샷 없음 ss1=%s(rc=%d) ss2=%s(rc=%d)",
               ss1, rc1, ss2, rc2);
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_INVALID);
        tx_buf_sets(ctx->out, "FOUND1", rc1 == TX_OK ? "Y" : "N");
        tx_buf_sets(ctx->out, "FOUND2", rc2 == TX_OK ? "Y" : "N");
        tx_buf_sets(ctx->out, "MESSAGE", "비교 대상 스냅샷 누락");
        tx_return(ctx, TX_ENOENT, ctx->out);
        return;
    }
    if (rc1 != TX_OK || rc2 != TX_OK) {
        tx_log(TX_LOG_ERROR, "[CL_OL_0031] 스냅샷 조회 실패 rc1=%d rc2=%d", rc1, rc2);
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_SYSERR);
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }

    /* 3) 금액/건수 차이, 방향, 변동률(기준 SS1) 산출 */
    diff     = rec2.amount - rec1.amount;   /* SS1 -> SS2 변동 */
    cnt_diff = rec2.fee - rec1.fee;
    if (diff > 0)
        direction = "UP";
    else if (diff < 0)
        direction = "DOWN";
    else
        direction = "FLAT";
    rate = (rec1.amount != 0)
             ? (diff * 100 / (rec1.amount < 0 ? -rec1.amount : rec1.amount))
             : 0;
    abs_diff = (diff < 0) ? -diff : diff;
    amount_format_won(diff, diff_won, sizeof(diff_won));

    /* 4) 비교 결과 요약 문구 구성 */
    snprintf(summary, sizeof(summary),
             "스냅샷 %s(%ld) -> %s(%ld) 변동 %ld원 (%s %ld%%)",
             ss1, rec1.amount, ss2, rec2.amount, diff, direction, rate);

    /* 5) 비교 결과를 cl_snap_diff 에 적재하여 감사이력으로 남긴다. */
    strncpy(h_ss1, ss1, sizeof(h_ss1) - 1);
    h_ss1[sizeof(h_ss1) - 1] = '\0';
    strncpy(h_ss2, ss2, sizeof(h_ss2) - 1);
    h_ss2[sizeof(h_ss2) - 1] = '\0';
    strncpy(h_direction, direction, sizeof(h_direction) - 1);
    h_direction[sizeof(h_direction) - 1] = '\0';
    strncpy(h_reqid, reqid, sizeof(h_reqid) - 1);
    h_reqid[sizeof(h_reqid) - 1] = '\0';
    h_diff = diff;

    if (tx_begin() != TX_OK) {
        tx_log(TX_LOG_WARN, "[CL_OL_0031] tx_begin 경고");
    } else {
        EXEC SQL INSERT INTO cl_snap_diff
                (ss1_key, ss2_key, amt_diff, direction, reqid, cmp_ts)
            VALUES (:h_ss1, :h_ss2, :h_diff, :h_direction, :h_reqid, now());

        if (sqlca.sqlcode != TX_SQL_OK) {
            TX_DBIO_LOG_ERR("CL_OL_0031 INSERT cl_snap_diff");
            tx_abort();
        } else {
            persisted = (long)sqlca.sqlerrd[2];
            tx_commit();
        }
    }

    tx_buf_reset(ctx->out);
    tx_buf_sets(ctx->out, "RESPCODE", RESP_OK);
    tx_buf_sets(ctx->out, "SS1", ss1);
    tx_buf_sets(ctx->out, "SS2", ss2);
    tx_buf_sets(ctx->out, "REQID", reqid);
    tx_buf_setlong(ctx->out, "AMT1", rec1.amount);
    tx_buf_setlong(ctx->out, "AMT2", rec2.amount);
    tx_buf_setlong(ctx->out, "CNT1", rec1.fee);
    tx_buf_setlong(ctx->out, "CNT2", rec2.fee);
    tx_buf_setlong(ctx->out, "DIFF", diff);
    tx_buf_sets(ctx->out, "DIFFWON", diff_won);
    tx_buf_setlong(ctx->out, "ABSDIFF", abs_diff);
    tx_buf_setlong(ctx->out, "CNTDIFF", cnt_diff);
    tx_buf_setlong(ctx->out, "RATE", rate);
    tx_buf_sets(ctx->out, "DIRECTION", direction);
    tx_buf_setlong(ctx->out, "PERSISTED", persisted);
    tx_buf_sets(ctx->out, "SUMMARY", summary);
    tx_buf_sets(ctx->out, "MATCH", (diff == 0) ? "Y" : "N");
    /* 유의미 변동 여부(절대변동이 기준의 1% 초과) */
    tx_buf_sets(ctx->out, "MATERIAL",
                (rate > 1 || rate < -1) ? "Y" : "N");

    tx_log(TX_LOG_INFO,
           "[CL_OL_0031] 완료 ss1=%s(%ld) ss2=%s(%ld) 차이=%ld 방향=%s",
           ss1, rec1.amount, ss2, rec2.amount, diff, direction);
    tx_return(ctx, TX_OK, ctx->out);
}
