/*
 * AUTH_PARTCXL.pgc - au 모듈 서비스 AUTH_PARTCXL (one service = one file).
 * 부분 취소: 승인 금액 감액 + 한도 부분 원복.
 * Moved verbatim from the former inline au_svr.pgc; runs on the caller's XA
 * branch (no EXEC SQL CONNECT). Advertised by au_svr at tpsvrinit.
 */
#include "AUTH_PARTCXL.h"

void AUTH_PARTCXL(TPSVCINFO *p)
{
    UBFH *b = (UBFH *)p->data;
    char card[24], bizdate[16];
    EXEC SQL BEGIN DECLARE SECTION;
    long h_id, h_auth, h_amt, h_new;
    char h_bizdate[16];
    EXEC SQL END DECLARE SECTION;

    h_auth = getl(b, T_ID1);
    h_amt = getl(b, T_AMOUNT);          /* 취소 금액 */
    gets_(b, T_KEY1, card, sizeof(card));
    gets_(b, T_BIZDATE, bizdate, sizeof(bizdate));
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;

    EXEC SQL SELECT amount INTO :h_new FROM au_authorization WHERE auth_id = :h_auth;
    if (sqlca.sqlcode < 0 || sqlca.sqlcode == 100) FAIL(b);
    h_new = h_new - h_amt;
    EXEC SQL SELECT nextval('au_cancel_seq') INTO :h_id;
    if (sqlca.sqlcode < 0) FAIL(b);
    EXEC SQL INSERT INTO au_cancel (cancel_id, auth_id, cancel_type, amount, reason, biz_date)
        VALUES (:h_id, :h_auth, 'PARTIAL', :h_amt, 'PARTIAL', :h_bizdate);
    if (sqlca.sqlcode < 0) FAIL(b);
    if (audb_update_auth_amount(h_auth, h_new) < 0) FAIL(b);
    if (card[0] && audb_limit_dec(card, -h_amt) < 0) FAIL(b);
    setl(b, T_CANCEL_ID, h_id);
    setl(b, T_AMOUNT, h_new);
    OK(b);
}
