/* @tier easy @module rc @transform reconciliation-online */
/*
 * rc_ol_0012.pgc - 가맹점별 대사 조회 (CURSOR) 온라인 서비스 (RC_OL_0012)
 *
 * 요청 MERCHID(가맹점번호) 의 원장을 처리키 순으로 커서 순회하며 상태별
 * 건수와 금액을 집계한다.
 * 업무규칙:
 *   - 총건수(CNT), 금액합계(SUMAMT) 누적
 *   - 상태별: 매입확정('M')=DONE, 불일치/보류('U')=UNMATCH,
 *             정산완료('S')=SETTLED
 *   - 대사완료율 RECRATE = (DONE + SETTLED) * 100 / CNT (0 나눗셈 방어)
 * 응답 MERCHID, CNT, DONE, UNMATCH, SETTLED, SUMAMT, RECRATE. (읽기 전용)
 */
#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_0012, ctx)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_merch_id[16];
    char h_status[2];
    long h_amount;
    EXEC SQL END DECLARE SECTION;

    char merchid[16];
    long cnt = 0, done = 0, unmatch = 0, settled = 0;
    long sumamt = 0, recrate = 0;
    int  opened = 0;

    tx_log(TX_LOG_INFO, "[RC_OL_0012] 가맹점별 대사 조회 서비스 진입");

    if (tx_buf_get(ctx->in, "MERCHID", merchid, sizeof(merchid)) != TX_OK) {
        tx_log(TX_LOG_ERROR, "[RC_OL_0012] MERCHID 누락");
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

    memset(h_merch_id, 0, sizeof(h_merch_id));
    strncpy(h_merch_id, merchid, sizeof(h_merch_id) - 1);

    EXEC SQL DECLARE cur_rc_ol_0012 CURSOR FOR
        SELECT status, amount
        FROM rc_ledger
        WHERE merch_id = :h_merch_id
        ORDER BY key;

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

    for (;;) {
        EXEC SQL FETCH cur_rc_ol_0012 INTO :h_status, :h_amount;

        if (sqlca.sqlcode == TX_SQL_NOTFOUND)
            break;
        if (sqlca.sqlcode != TX_SQL_OK) {
            TX_DBIO_LOG_ERR("FETCH cur_rc_ol_0012");
            break;
        }

        cnt++;
        sumamt += h_amount;

        if (strcmp(h_status, RC_ST_DONE) == 0)
            done++;
        else if (strcmp(h_status, RC_ST_FAIL) == 0)
            unmatch++;
        else if (strcmp(h_status, RC_ST_SETTLED) == 0)
            settled++;
    }

    if (opened)
        EXEC SQL CLOSE cur_rc_ol_0012;

    recrate = (cnt > 0) ? ((done + settled) * 100 / cnt) : 0;

    tx_buf_reset(ctx->out);
    tx_buf_sets(ctx->out, "MERCHID", merchid);
    tx_buf_setlong(ctx->out, "CNT", cnt);
    tx_buf_setlong(ctx->out, "DONE", done);
    tx_buf_setlong(ctx->out, "UNMATCH", unmatch);
    tx_buf_setlong(ctx->out, "SETTLED", settled);
    tx_buf_setlong(ctx->out, "SUMAMT", sumamt);
    tx_buf_setlong(ctx->out, "RECRATE", recrate);
    tx_log(TX_LOG_INFO,
           "[RC_OL_0012] 가맹점별 집계 merch=%s 건수=%ld 완료율=%ld%%",
           merchid, cnt, recrate);
    tx_return(ctx, TX_OK, ctx->out);
}
