/*
 * MM_LIMIT_SET.pgc - mm 모듈 서비스 MM_LIMIT_SET (one service = one file).
 * 기능: 가맹점 한도 설정 (upsert).
 * 기존 인라인 mm_svr.pgc에서 분리; caller의 XA 브랜치에서 실행(EXEC SQL CONNECT 없음).
 * mm_svr가 tpsvrinit에서 이 서비스를 tpadvertise 한다.
 */
#include "MM_LIMIT_SET.h"

void MM_LIMIT_SET(TPSVCINFO *p)
{
    UBFH *b = (UBFH *)p->data;
    EXEC SQL BEGIN DECLARE SECTION;
    long h_daily, h_monthly, h_pertxn;
    char h_merch[64];
    EXEC SQL END DECLARE SECTION;
    char merch[64];
    gets_(b, T_MERCHANT, merch, sizeof(merch));
    strncpy(h_merch, merch, sizeof(h_merch)-1); h_merch[sizeof(h_merch)-1] = 0;
    h_daily   = getl(b, T_AMT1); if (h_daily   <= 0) h_daily   = 100000000;
    h_monthly = getl(b, T_AMT2); if (h_monthly <= 0) h_monthly = h_daily * 30;
    h_pertxn  = getl(b, T_AMT3); if (h_pertxn  <= 0) h_pertxn  = 10000000;

    EXEC SQL INSERT INTO mm_limit
        (merchant_id, daily_limit, monthly_limit, per_txn_limit)
        VALUES (:h_merch, :h_daily, :h_monthly, :h_pertxn)
        ON CONFLICT (merchant_id) DO UPDATE
        SET daily_limit = EXCLUDED.daily_limit, monthly_limit = EXCLUDED.monthly_limit,
            per_txn_limit = EXCLUDED.per_txn_limit, updated_at = now();
    if (sqlca.sqlcode < 0) { userlog("MM_LIMIT_SET FAIL [%d] %s", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); FAIL(b); }
    OK(b);
}
