/*
 * ac_wht_distinct_dbio.pgc - ac 모듈 DB 접근 함수 세트 (ac_wht_distinct_dbio), archived into libacdbio.a.
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 * Shape: count(DISTINCT purchase_id) 와 sum(tax_amount) 를 한 번에 산출하여 구조체로 반환.
 */
#include <string.h>
#include <userlog.h>
#include "ac_wht_distinct_dbio.h"

/* 원천징수가 걸린 서로 다른 매입 수와 총 원천세액을 out 에 채운다. */
int acdb_wht_distinct_summary(const char *bizdate, ac_wht_distinct_rec_t *out)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_dp = 0, h_tax = 0;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL SELECT count(DISTINCT purchase_id), coalesce(sum(tax_amount),0)
        INTO :h_dp, :h_tax FROM ac_wht WHERE biz_date = :h_bizdate;
    if (sqlca.sqlcode < 0) {
        userlog("acdb_wht_distinct_summary FAIL [%d] %s", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc);
        return -1;
    }
    out->distinct_purchases = h_dp;
    out->total_tax = h_tax;
    return 0;
}
