/*
 * ACQ_SETTLELINK.pgc - ac 모듈 서비스 ACQ_SETTLELINK (one service = one file).
 * 정산 연계: 가맹점 미지정 시 매입에서 조회, settlement 링크 행(status='LINKED') 생성.
 * Runs on the caller's XA branch (no EXEC SQL CONNECT). Advertised by ac_svr.
 */
#include "ACQ_SETTLELINK.h"

void ACQ_SETTLELINK(TPSVCINFO *p)
{
    UBFH *b = (UBFH *)p->data;
    char merch[64], bizdate[16];
    EXEC SQL BEGIN DECLARE SECTION;
    long h_id, h_pid, h_net;
    char h_merch[64], h_bizdate[16];
    EXEC SQL END DECLARE SECTION;

    h_pid = getl(b, T_PURCHASE_ID);
    h_net = getl(b, T_NET);
    gets_(b, T_MERCHANT, merch, sizeof(merch));
    gets_(b, T_BIZDATE, bizdate, sizeof(bizdate));
    if (merch[0] == 0) {
        EXEC SQL SELECT merchant_id INTO :h_merch FROM purchase WHERE purchase_id = :h_pid;
        if (sqlca.sqlcode < 0 || sqlca.sqlcode == 100) FAIL(b);
    } else {
        strncpy(h_merch, merch, sizeof(h_merch)-1); h_merch[sizeof(h_merch)-1] = 0;
    }
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;

    EXEC SQL SELECT nextval('settlement_seq') INTO :h_id;
    if (sqlca.sqlcode < 0) FAIL(b);
    EXEC SQL INSERT INTO settlement (settlement_id, purchase_id, merchant_id, net, biz_date, status)
        VALUES (:h_id, :h_pid, :h_merch, :h_net, :h_bizdate, 'LINKED');
    if (sqlca.sqlcode < 0) { userlog("ACQ_SETTLELINK FAIL [%d] %s", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); FAIL(b); }
    setl(b, T_SETTLE_ID, h_id);
    OK(b);
}
