#include <stdio.h>
#include <string.h>
#include <atmi.h>
#include <ubf.h>
#include <userlog.h>
#include "acq.fd.h"

void ACQUIRE(TPSVCINFO *p);   /* forward decl */

/* 서버 프로세스 초기화/종료 콜백 (ATMI 필수) */
int tpsvrinit(int argc, char **argv)
{
    if (tpadvertise("ACQUIRE", ACQUIRE) < 0) {
        userlog("acqsv: tpadvertise(ACQUIRE) FAIL: %s", tpstrerror(tperrno));
        return -1;
    }
    userlog("acqsv: tpsvrinit - ACQUIRE 서비스 advertise 완료");
    return 0;
}

void tpsvrdone(void)
{
    userlog("acqsv: tpsvrdone - 종료");
}

void ACQUIRE(TPSVCINFO *p)
{
    UBFH *b = (UBFH *)p->data;
    long amount = 0, fee, net;
    char merch[64] = "";
    BFLDLEN len = sizeof(merch);

    if (Bget(b, T_MERCHANT, 0, merch, &len) < 0) {
        userlog("ACQUIRE: missing T_MERCHANT: %s", Bstrerror(Berror));
        tpreturn(TPFAIL, 0, p->data, 0L, 0L);
        return;
    }
    Bget(b, T_AMOUNT, 0, (char *)&amount, 0L);

    fee = amount * 25 / 10000;   /* 0.25% MDR 수수료 */
    net = amount - fee;

    Bchg(b, T_FEE, 0, (char *)&fee, 0L);
    Bchg(b, T_NET, 0, (char *)&net, 0L);
    Bchg(b, T_STATUS, 0, "ACQUIRED", 0L);

    userlog("ACQUIRE merch=%s amount=%ld fee=%ld net=%ld", merch, amount, fee, net);
    tpreturn(TPSUCCESS, 0, p->data, 0L, 0L);
}
