/*
 * au_summary_rebuild_dbio.pgc - au 모듈 DB 접근 함수 세트 (au_summary_rebuild_dbio), archived into libaudbio.a.
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 * Shape: INSERT INTO au_summary SELECT count(*) FILTER (...) GROUP BY ... ON CONFLICT DO UPDATE.
 */
#include <string.h>
#include <userlog.h>
#include "au_summary_rebuild_dbio.h"

/* 당일 au_authorization 을 가맹점별 승인/거절/금액으로 재집계하여 au_summary 에 upsert. */
long audb_summary_rebuild_from_auth(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 au_summary
        (merchant_id, biz_date, auth_count, approve_count, decline_count, auth_amount)
        SELECT merchant_id, biz_date, count(*),
               count(*) FILTER (WHERE status = 'A'),
               count(*) FILTER (WHERE status = 'D'),
               coalesce(sum(amount),0)
        FROM au_authorization WHERE biz_date = :h_bizdate
        GROUP BY merchant_id, biz_date
        ON CONFLICT (merchant_id, biz_date) DO UPDATE
        SET auth_count = EXCLUDED.auth_count,
            approve_count = EXCLUDED.approve_count,
            decline_count = EXCLUDED.decline_count,
            auth_amount = EXCLUDED.auth_amount,
            updated_at = now();
    if (sqlca.sqlcode < 0) {
        userlog("audb_summary_rebuild_from_auth FAIL [%d] %s", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc);
        return -1;
    }
    affected = sqlca.sqlerrd[2];
    return affected;
}
