/*
 * ac_summary_rebuild_dbio.pgc - ac 모듈 DB 접근 함수 세트 (ac_summary_rebuild_dbio), archived into libacdbio.a.
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 * Shape: INSERT INTO merchant_summary SELECT ... GROUP BY ... ON CONFLICT DO UPDATE (재집계 upsert).
 */
#include <string.h>
#include <userlog.h>
#include "ac_summary_rebuild_dbio.h"

/* 당일 purchase 를 가맹점별로 재집계하여 merchant_summary 에 upsert. 반영 행수 반환. */
long acdb_summary_rebuild_from_purchase(const char *bizdate)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long affected = 0;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL INSERT INTO merchant_summary
        (merchant_id, biz_date, txn_count, gross_amount, fee_amount, net_amount)
        SELECT merchant_id, biz_date, count(*), coalesce(sum(amount),0),
               coalesce(sum(fee),0), coalesce(sum(net),0)
        FROM purchase WHERE biz_date = :h_bizdate
        GROUP BY merchant_id, biz_date
        ON CONFLICT (merchant_id, biz_date) DO UPDATE
        SET txn_count = EXCLUDED.txn_count,
            gross_amount = EXCLUDED.gross_amount,
            fee_amount = EXCLUDED.fee_amount,
            net_amount = EXCLUDED.net_amount,
            updated_at = now();
    if (sqlca.sqlcode < 0) {
        userlog("acdb_summary_rebuild_from_purchase FAIL [%d] %s", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc);
        return -1;
    }
    affected = sqlca.sqlerrd[2];
    return affected;
}
