/*
 * rc_ledger_dbio.pgc - 대사 원장 연계 + 요약 upsert DB 접근 (librcdbio.a).
 * ECPG 함수; 호출자의 XA 브랜치에서 수행. EXEC SQL CONNECT 없음.
 */
#include <string.h>
#include <userlog.h>
#include "rc_dbio.h"

long rcdb_count_unmatched(const char *bizdate)
{
    EXEC SQL BEGIN DECLARE SECTION;
    long h_cnt;
    char h_bizdate[16];
    EXEC SQL END DECLARE SECTION;

    strncpy(h_bizdate, bizdate, sizeof(h_bizdate) - 1); h_bizdate[sizeof(h_bizdate)-1] = 0;

    EXEC SQL SELECT count(*) INTO :h_cnt FROM purchase p
        WHERE p.biz_date = :h_bizdate
          AND NOT EXISTS (SELECT 1 FROM ledger l WHERE l.purchase_id = p.purchase_id);
    if (sqlca.sqlcode < 0) {
        userlog("rcdb_count_unmatched FAIL [%d] %s", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc);
        return -1;
    }
    return h_cnt;
}

long rcdb_insert_ledger(long pid, const char *type, long amount, const char *bizdate)
{
    EXEC SQL BEGIN DECLARE SECTION;
    long h_pid = pid, h_amount = amount;
    char h_type[16], h_bizdate[16];
    EXEC SQL END DECLARE SECTION;

    strncpy(h_type, type, sizeof(h_type) - 1);          h_type[sizeof(h_type)-1] = 0;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate) - 1); h_bizdate[sizeof(h_bizdate)-1] = 0;

    EXEC SQL INSERT INTO ledger (ledger_id, purchase_id, entry_type, amount, biz_date)
        VALUES (nextval('ledger_seq'), :h_pid, :h_type, :h_amount, :h_bizdate);
    if (sqlca.sqlcode < 0) {
        userlog("rcdb_insert_ledger FAIL [%d] %s", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc);
        return -1;
    }
    return 0;
}

int rcdb_upsert_summary(const char *bizdate, long matched, long unmatched, long gross)
{
    EXEC SQL BEGIN DECLARE SECTION;
    long h_matched = matched, h_unmatched = unmatched, h_gross = gross;
    char h_bizdate[16];
    EXEC SQL END DECLARE SECTION;

    strncpy(h_bizdate, bizdate, sizeof(h_bizdate) - 1); h_bizdate[sizeof(h_bizdate)-1] = 0;

    EXEC SQL INSERT INTO rc_summary (biz_date, matched_cnt, unmatched_cnt, gross_amount)
        VALUES (:h_bizdate, :h_matched, :h_unmatched, :h_gross)
        ON CONFLICT (biz_date) DO UPDATE
        SET matched_cnt = EXCLUDED.matched_cnt,
            unmatched_cnt = EXCLUDED.unmatched_cnt,
            gross_amount = EXCLUDED.gross_amount,
            updated_at = now();
    if (sqlca.sqlcode < 0) {
        userlog("rcdb_upsert_summary FAIL [%d] %s", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc);
        return -1;
    }
    return 0;
}
