/*
 * ACQUIRE.pgc - ac 모듈 서비스 ACQUIRE (one service = one file).
 * Moved verbatim from the former inline ac_svr.pgc; runs on the caller's XA
 * branch (no EXEC SQL CONNECT). Advertised by ac_svr at tpsvrinit.
 */
#include "ACQUIRE.h"

void ACQUIRE(TPSVCINFO *p)
{
    UBFH *b = (UBFH *)p->data;
    char merch[64], bizdate[16];
    long amount, bps = 25, fee, net, pid, rlen = 0;

    gets_(b, T_MERCHANT, merch, sizeof(merch));
    if (merch[0] == 0) { userlog("ACQUIRE: missing T_MERCHANT"); FAIL(b); }
    amount = getl(b, T_AMOUNT);
    gets_(b, T_BIZDATE, bizdate, sizeof(bizdate));

    if (acdb_merchant_mdr(merch, &bps) < 0) bps = 25;   /* keep 25bps default */
    fee = acq_fee(amount, bps);
    net = amount - fee;

    pid = acdb_next_purchase_id();
    if (pid < 0) FAIL(b);
    if (acdb_insert_purchase(pid, merch, amount, fee, net, "A", "POS", bizdate) < 0) FAIL(b);
    if (acdb_insert_approval(pid, 1) < 0) FAIL(b);

    setl(b, T_PURCHASE_ID, pid);
    setl(b, T_FEE, fee);
    setl(b, T_NET, net);
    Bchg(b, T_STATUS, 0, "A", 0L);

    userlog("ACQUIRE pid=%ld merch=%s amount=%ld fee=%ld net=%ld -> RECONCILE",
            pid, merch, amount, fee, net);

    /* continue the SAME global tx into rc_svr (distinct branch) */
    if (tpcall("RECONCILE", (char *)b, 0L, (char **)&b, &rlen, 0L) < 0) {
        userlog("ACQUIRE: tpcall(RECONCILE) FAIL: %s", tpstrerror(tperrno));
        FAIL(b);
    }
    /* our branch resumes: settle-complete the purchase we own */
    if (acdb_update_status(pid, "S") < 0) FAIL(b);
    Bchg(b, T_STATUS, 0, "S", 0L);
    OK(b);
}
