/*
 * ACQ_FOREIGN.pgc - ac 모듈 서비스 ACQ_FOREIGN (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 "ACQ_FOREIGN.h"

void ACQ_FOREIGN(TPSVCINFO *p)
{
    UBFH *b = (UBFH *)p->data;
    char merch[64], bizdate[16], ccy[8];
    long amount, bps = 30, fee, net, pid;
    EXEC SQL BEGIN DECLARE SECTION;
    long h_id, h_pid, h_fx, h_krw, h_rate;
    char h_ccy[8], h_bizdate[16];
    EXEC SQL END DECLARE SECTION;

    gets_(b, T_MERCHANT, merch, sizeof(merch));
    amount = getl(b, T_AMOUNT);
    gets_(b, T_BIZDATE, bizdate, sizeof(bizdate));
    gets_(b, T_CCY, ccy, sizeof(ccy)); if (ccy[0] == 0) strcpy(ccy, "USD");
    if (acdb_merchant_mdr(merch, &bps) < 0) bps = 30;
    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", "FOREIGN", bizdate) < 0) FAIL(b);

    h_pid = pid; h_fx = amount; h_rate = 1350; h_krw = amount;
    strncpy(h_ccy, ccy, sizeof(h_ccy)-1); h_ccy[sizeof(h_ccy)-1] = 0;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL SELECT nextval('ac_fx_seq') INTO :h_id;
    if (sqlca.sqlcode < 0) FAIL(b);
    EXEC SQL INSERT INTO ac_fx (fx_id, purchase_id, ccy, fx_amount, krw_amount, rate_bps, biz_date)
        VALUES (:h_id, :h_pid, :h_ccy, :h_fx, :h_krw, :h_rate, :h_bizdate);
    if (sqlca.sqlcode < 0) FAIL(b);
    setl(b, T_PURCHASE_ID, pid); setl(b, T_FEE, fee);
    OK(b);
}
