/*
 * rc_backfill_batch.pgc - rc 당일 요약 백필 (집계 + upsert + XA).
 *
 * rc_match_log 를 집계해 rc_summary 를 ON CONFLICT upsert 로 재구성. 두 문장을 하나의
 * 글로벌 트랜잭션에 묶어 2PC 로 커밋. 사용법: rc_backfill_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "rc_dbio.h"
#include "rc_backfill_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    rc_backfill_rec_t rec; rec.matched = 0; rec.gross = 0;

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_matched, h_gross;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;

    if (tpinit(NULL) < 0) { fprintf(stderr, "tpinit FAIL: %s\n", tpstrerror(tperrno)); return 1; }
    if (tpopen() < 0)     { fprintf(stderr, "tpopen FAIL: %s\n", tpstrerror(tperrno)); return 1; }
    if (tpbegin(60, 0) < 0) { fprintf(stderr, "tpbegin FAIL: %s\n", tpstrerror(tperrno)); return 1; }

    EXEC SQL SELECT count(*) FILTER (WHERE status = 'MATCHED'), coalesce(sum(amount), 0)
        INTO :h_matched, :h_gross FROM rc_match_log WHERE biz_date = :h_bizdate;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "AGG FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    rec.matched = h_matched; rec.gross = h_gross;

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

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> %s COMMIT: bizdate=%s matched=%ld gross=%ld\n", RC_BACKFILL_TAG, bizdate, rec.matched, rec.gross);

    tpclose(); tpterm();
    return 0;
}
