/*
 * py_summary_gap_dbio.pgc - py 모듈 DB 접근 함수 세트 (py_summary_gap_dbio), archived into libpydbio.a.
 * 집계 테이블에 적재된 금액과 원장 실집계 금액의 차이를 대조한다.
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 */
#include <string.h>
#include <userlog.h>
#include "py_summary_gap_dbio.h"

/* 집계 vs 실집계 대조: 적재금액, 실집계금액, 차액을 반환. */
int pydb_summary_gap(const char *merch, const char *bizdate,
                     long *recorded, long *live, long *gap)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_merch[64], h_bizdate[16];
    long h_rec = 0, h_live = 0;
    EXEC SQL END DECLARE SECTION;
    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 coalesce(payout_amount,0) INTO :h_rec FROM py_summary
        WHERE merchant_id = :h_merch AND biz_date = :h_bizdate;
    if (sqlca.sqlcode < 0 && sqlca.sqlcode != 100) return -1;
    if (sqlca.sqlcode == 100) h_rec = 0;
    EXEC SQL SELECT coalesce(sum(amount),0) INTO :h_live FROM py_payout
        WHERE merchant_id = :h_merch AND biz_date = :h_bizdate;
    if (sqlca.sqlcode < 0) { userlog("pydb_summary_gap FAIL [%d] %s", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); return -1; }
    *recorded = h_rec; *live = h_live; *gap = h_live - h_rec;
    return 0;
}
