/*
 * AUTH.pgc - au 모듈 서비스 AUTH (one service = one file).
 * 승인 접수: 한도 점검 후 authorization 원장 기록 + 한도 차감.
 * 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.h"

void AUTH(TPSVCINFO *p)
{
    UBFH *b = (UBFH *)p->data;
    char card[24], merch[64], bizdate[16], appr[12];
    long amount, auth_id, lim = 0, used = 0;

    gets_(b, T_KEY1, card, sizeof(card));
    if (card[0] == 0) { userlog("AUTH: T_KEY1(카드번호) 누락"); FAIL(b); }
    gets_(b, T_MERCHANT, merch, sizeof(merch));
    amount = getl(b, T_AMOUNT);
    gets_(b, T_BIZDATE, bizdate, sizeof(bizdate));

    /* 한도 점검: 초과면 거절(D) 상태로 기록 */
    if (audb_limit_get(card, &lim, &used) < 0) FAIL(b);
    if (used + amount > lim) {
        userlog("AUTH 한도초과 card=%s used=%ld amt=%ld lim=%ld -> 거절", card, used, amount, lim);
        auth_id = audb_next_auth_id();
        if (auth_id < 0) FAIL(b);
        if (audb_insert_auth(auth_id, card, merch, amount, "000000", "AUTH", "D", bizdate) < 0) FAIL(b);
        setl(b, T_ID1, auth_id);
        setl(b, T_RC, 1);
        Bchg(b, T_STATUS, 0, "D", 0L);
        OK(b);
    }
    auth_id = audb_next_auth_id();
    if (auth_id < 0) FAIL(b);
    sprintf(appr, "%06ld", auth_id % 1000000);
    if (audb_insert_auth(auth_id, card, merch, amount, appr, "AUTH", "A", bizdate) < 0) FAIL(b);
    if (audb_limit_dec(card, amount) < 0) FAIL(b);

    setl(b, T_ID1, auth_id);
    setl(b, T_RC, 0);
    Bchg(b, T_STR2, 0, appr, 0L);
    Bchg(b, T_STATUS, 0, "A", 0L);
    userlog("AUTH 승인 auth_id=%ld card=%s merch=%s amt=%ld appr=%s", auth_id, card, merch, amount, appr);
    OK(b);
}
