/*
 * PAY_REPROC.pgc - py 모듈 서비스 PAY_REPROC (one service = one file).
 * 재처리: 직전 상태를 조회한 뒤 실패/보류/취소(J,H,C) -> 요청(R) 전이, 이전 상태 회신.
 * SELECT prev status then UPDATE with IN(...) guard, report the transition.
 * Runs on the caller's XA branch (no EXEC SQL CONNECT). Advertised by py_svr.
 */
#include "PAY_REPROC.h"

void PAY_REPROC(TPSVCINFO *p)
{
    UBFH *b = (UBFH *)p->data;
    EXEC SQL BEGIN DECLARE SECTION;
    long h_pay, h_aff;
    char h_prev[8];
    EXEC SQL END DECLARE SECTION;

    h_pay = getl(b, T_ID1);
    EXEC SQL SELECT status INTO :h_prev FROM py_payout WHERE payout_id = :h_pay;
    if (sqlca.sqlcode < 0 || sqlca.sqlcode == 100) FAIL(b);
    /* reprocess only failed/held/cancelled; report whether the transition fired */
    EXEC SQL UPDATE py_payout SET status = 'R', retry_count = retry_count + 1, updated_at = now()
        WHERE payout_id = :h_pay AND status IN ('J', 'H', 'C');
    if (sqlca.sqlcode < 0) FAIL(b);
    h_aff = sqlca.sqlerrd[2];
    Bchg(b, T_STATUS, 0, h_aff > 0 ? "R" : h_prev, 0L);
    setl(b, T_RC, h_aff > 0 ? 0 : 1);
    OK(b);
}
