/*
 * ac_merch_dbio.pgc - merchant lookup + daily summary upsert (libacdbio.a).
 */
#include <string.h>
#include <userlog.h>
#include "ac_dbio.h"

int acdb_merchant_mdr(const char *merch, long *bps_out)
{
    EXEC SQL BEGIN DECLARE SECTION;
    long h_bps;
    char h_merch[64];
    EXEC SQL END DECLARE SECTION;

    strncpy(h_merch, merch, sizeof(h_merch) - 1); h_merch[sizeof(h_merch)-1] = 0;

    EXEC SQL SELECT mdr_bps INTO :h_bps FROM merchant WHERE merchant_id = :h_merch;
    if (sqlca.sqlcode < 0 || sqlca.sqlcode == 100) {
        userlog("acdb_merchant_mdr FAIL [%d] %s", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc);
        return -1;
    }
    *bps_out = h_bps;
    return 0;
}

int acdb_upsert_merch_sum(const char *merch, const char *bizdate, long gross,
                          long fee, long net, long cnt)
{
    EXEC SQL BEGIN DECLARE SECTION;
    long h_gross = gross, h_fee = fee, h_net = net, h_cnt = cnt;
    char h_merch[64], h_bizdate[16];
    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 INSERT INTO merchant_summary
        (merchant_id, biz_date, txn_count, gross_amount, fee_amount, net_amount)
        VALUES (:h_merch, :h_bizdate, :h_cnt, :h_gross, :h_fee, :h_net)
        ON CONFLICT (merchant_id, biz_date) DO UPDATE
        SET txn_count = merchant_summary.txn_count + EXCLUDED.txn_count,
            gross_amount = merchant_summary.gross_amount + EXCLUDED.gross_amount,
            fee_amount = merchant_summary.fee_amount + EXCLUDED.fee_amount,
            net_amount = merchant_summary.net_amount + EXCLUDED.net_amount,
            updated_at = now();
    if (sqlca.sqlcode < 0) {
        userlog("acdb_upsert_merch_sum FAIL [%d] %s", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc);
        return -1;
    }
    return 0;
}
