/*
 * ACQ_PRESENT.pgc - ac 모듈 서비스 ACQ_PRESENT (one service = one file).
 * 프레젠트먼트(클리어링) 생성. 승인·정산과 분리된 데이터 교환 단계로, 발급사↔매입사
 * 채무를 확정한다. 수수료 3층 분해(st_fee_component)의 interchange 는 발급사 귀속분이므로
 * 클리어링 대상 금액은 clearing_amt = amount − interchange 이다.
 * 같은 매입에 FIRST_PRESENT 가 이미 있으면 msg_class 를 REPRESENT 로 승격한다.
 * 입출력 계약: 입력 T_PURCHASE_ID [+ T_STR1(scheme)/T_AMOUNT/T_AMT1(interchange)/T_BIZDATE],
 *             출력 T_ID1(presentment_id) / T_AMT1(clearing_amt) / T_STATUS='CLEARED'.
 * Runs on the caller's XA branch (no EXEC SQL CONNECT). Advertised by ac_svr.
 */
#include "ACQ_PRESENT.h"

void ACQ_PRESENT(TPSVCINFO *p)
{
    UBFH *b = (UBFH *)p->data;
    const char *SVC = "ACQ_PRESENT";
    char bizdate[16], scheme[16], msgclass[24], cycle[12], logmsg[256];
    long clearing = 0, has_fc = 0;
    EXEC SQL BEGIN DECLARE SECTION;
    long h_pid, h_amt, h_ic, h_clr, h_prid, h_logid, h_cnt, h_prev;
    char h_bizdate[16], h_scheme[16], h_msgclass[24], h_cycle[12], h_merch[64], h_logmsg[256];
    EXEC SQL END DECLARE SECTION;

    /* 지역/호스트 변수 초기화 (DECLARE SECTION 밖) */
    h_pid = h_amt = h_ic = h_clr = h_prid = h_logid = h_cnt = h_prev = 0;
    bizdate[0] = logmsg[0] = 0;
    strcpy(scheme, "BC"); strcpy(cycle, "T+1"); strcpy(msgclass, "FIRST_PRESENT");
    h_bizdate[0] = 0; strcpy(h_scheme, "BC"); strcpy(h_merch, "UNKNOWN");
    userlog("%s 진입: 프레젠트먼트(클리어링) 생성 요청", SVC);

    /* [1] 입력 검증부 -------------------------------------------------- */
    h_pid = getl(b, T_PURCHASE_ID);
    if (h_pid <= 0) {
        Bchg(b, T_MSG, 0, "매입 ID 오류", 0L); setl(b, T_RC, 7401); FAIL(b);
    }
    gets_(b, T_STR1, scheme, sizeof(scheme));
    if (scheme[0] == 0) strcpy(scheme, "BC");
    gets_(b, T_BIZDATE, bizdate, sizeof(bizdate));
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;

    /* [2] 수수료 분해 조회부 (XA 격리: 없으면 전문 amount/interchange, 100 은 정상흐름) */
    EXEC SQL SELECT amount, interchange, scheme INTO :h_amt, :h_ic, :h_scheme
        FROM st_fee_component WHERE purchase_id = :h_pid;
    if (sqlca.sqlcode < 0) {
        userlog("%s: 수수료 분해 조회 실패 [%d] %s", SVC, sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc);
        setl(b, T_RC, 90); FAIL(b);
    }
    if (sqlca.sqlcode == 100) {
        /* 분해 미산출/미커밋: 전문값으로 클리어링. interchange 미제공이면 0 */
        has_fc = 0;
        h_amt = getl(b, T_AMOUNT);
        h_ic  = getl(b, T_AMT1);
        strncpy(h_scheme, scheme, sizeof(h_scheme)-1); h_scheme[sizeof(h_scheme)-1] = 0;
        userlog("%s: st_fee_component 미존재 pid=%ld — 전문 amount=%ld ic=%ld 사용",
                SVC, h_pid, h_amt, h_ic);
    } else {
        has_fc = 1;
    }
    if (h_amt <= 0) h_amt = getl(b, T_AMOUNT);
    if (h_amt <= 0) {
        Bchg(b, T_MSG, 0, "클리어링 금액 산정 불가", 0L); setl(b, T_RC, 7402); FAIL(b);
    }
    if (h_ic < 0) h_ic = 0;
    if (h_ic > h_amt) h_ic = h_amt;             /* interchange 는 매출을 넘지 못함 */
    if (h_scheme[0] == 0) strcpy(h_scheme, "BC");

    /* 매입 원장에서 영업일/가맹점 보강 (미커밋이면 전문/파라미터 폴백) */
    EXEC SQL SELECT merchant_id, biz_date INTO :h_merch, :h_bizdate
        FROM purchase WHERE purchase_id = :h_pid;
    if (sqlca.sqlcode < 0) { setl(b, T_RC, 90); FAIL(b); }
    if (sqlca.sqlcode == 100) {
        gets_(b, T_MERCHANT, h_merch, sizeof(h_merch));
        if (h_merch[0] == 0) strcpy(h_merch, "UNKNOWN");
        userlog("%s: 매입 미커밋(체인) pid=%ld — 전문값 사용", SVC, h_pid);
    }
    if (h_bizdate[0] == 0) {
        EXEC SQL SELECT param_val INTO :h_bizdate FROM cm_param WHERE param_key = 'BIZ_DATE';
        if (sqlca.sqlcode != 0) strcpy(h_bizdate, "2026-07-19");
    }
    userlog("%s 컨텍스트: pid=%ld merch=%s amt=%ld ic=%ld scheme=%s fc=%ld",
            SVC, h_pid, h_merch, h_amt, h_ic, h_scheme, has_fc);

    /* [3] 업무규칙 분기부: 기존 프레젠트먼트 존재 여부로 msg_class 결정 ---- */
    EXEC SQL SELECT count(*) INTO :h_prev FROM cl_presentment
        WHERE purchase_id = :h_pid AND msg_class = 'FIRST_PRESENT';
    if (sqlca.sqlcode < 0) { setl(b, T_RC, 90); FAIL(b); }
    if (h_prev > 0) strcpy(msgclass, "REPRESENT");   /* 1차가 있으면 재프레젠트 */
    else            strcpy(msgclass, "FIRST_PRESENT");
    strncpy(h_msgclass, msgclass, sizeof(h_msgclass)-1); h_msgclass[sizeof(h_msgclass)-1] = 0;
    strncpy(h_cycle, cycle, sizeof(h_cycle)-1); h_cycle[sizeof(h_cycle)-1] = 0;

    /* 클리어링 금액 = 매출 − 발급사 귀속 interchange */
    clearing = h_amt - h_ic;
    if (clearing < 0) clearing = 0;
    h_clr = clearing;

    /* [4] 본처리부: cl_presentment INSERT (CLEARED) --------------------- */
    EXEC SQL SELECT nextval('cl_present_seq') INTO :h_prid;
    if (sqlca.sqlcode < 0) { setl(b, T_RC, 90); FAIL(b); }
    EXEC SQL INSERT INTO cl_presentment
        (presentment_id, purchase_id, scheme, msg_class, clearing_amt, present_date, cycle, status)
        VALUES (:h_prid, :h_pid, :h_scheme, :h_msgclass, :h_clr, :h_bizdate, :h_cycle, 'CLEARED');
    if (sqlca.sqlcode < 0) {
        userlog("%s: 프레젠트먼트 적재 실패 [%d] %s", SVC, sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc);
        setl(b, T_RC, 90); FAIL(b);
    }

    /* [5] 이력/감사 적재부 (cm_log) ------------------------------------- */
    snprintf(logmsg, sizeof(logmsg), "프레젠트먼트 prid=%ld pid=%ld class=%s clr=%ld ic=%ld",
             h_prid, h_pid, h_msgclass, clearing, h_ic);
    strncpy(h_logmsg, logmsg, sizeof(h_logmsg)-1); h_logmsg[sizeof(h_logmsg)-1] = 0;
    EXEC SQL SELECT nextval('cm_log_seq') INTO :h_logid;
    if (sqlca.sqlcode < 0) { setl(b, T_RC, 90); FAIL(b); }
    EXEC SQL INSERT INTO cm_log (log_id, svc_name, log_level, msg, biz_date)
        VALUES (:h_logid, 'ACQ_PRESENT', 'I', :h_logmsg, :h_bizdate);
    if (sqlca.sqlcode < 0) { setl(b, T_RC, 90); FAIL(b); }

    /* [6] 집계/요약부: 해당 매입 프레젠트먼트 총 건수 ------------------- */
    EXEC SQL SELECT count(*) INTO :h_cnt FROM cl_presentment WHERE purchase_id = :h_pid;
    if (sqlca.sqlcode < 0) { h_cnt = 0; }

    /* [7] 응답부 (계약 보존: T_ID1=presentment_id / T_AMT1=clearing_amt) - */
    setl(b, T_ID1, h_prid);
    setl(b, T_AMT1, clearing);
    setl(b, T_PURCHASE_ID, h_pid);
    setl(b, T_AMOUNT, h_amt);
    setl(b, T_FEE, h_ic);
    Bchg(b, T_STATUS, 0, "CLEARED", 0L);
    Bchg(b, T_STR1, 0, h_scheme, 0L);
    Bchg(b, T_STR2, 0, h_msgclass, 0L);
    Bchg(b, T_BIZDATE, 0, h_bizdate, 0L);
    Bchg(b, T_MERCHANT, 0, h_merch, 0L);
    setl(b, T_COUNT, h_cnt);
    Bchg(b, T_MSG, 0, "프레젠트먼트 생성(CLEARED)", 0L);
    setl(b, T_RC, 0);
    userlog("%s 완료: prid=%ld pid=%ld clr=%ld class=%s", SVC, h_prid, h_pid, clearing, h_msgclass);
    OK(b);
}

/* vim: set ts=4 sw=4 et smartindent: */
