/*
 * rc_windowload_batch.pgc - rc 유형 1순위 대사 -> rc_diff 적재 (윈도우 커서 + XA).
 *
 * ATMI client: tpinit/tpopen 로 ECPG XA RM 를 열고 tpbegin 으로 글로벌 tx 시작.
 * rank() OVER 커서로 유형별 최고금액(1순위) 대사를 골라 rc_diff 에 기준선으로 적재한 뒤
 * tpcommit 이 XA 2PC 를 구동. 사용법: rc_windowload_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "rc_dbio.h"
#include "rc_windowload_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    rc_windowload_rec_t rec;
    long loaded = 0;

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_pid, h_amt, h_rank;
    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 DECLARE wlc CURSOR FOR
        SELECT purchase_id, amount,
               rank() OVER (PARTITION BY match_type ORDER BY amount DESC)
        FROM rc_match_log WHERE biz_date = :h_bizdate;
    EXEC SQL OPEN wlc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH wlc INTO :h_pid, :h_amt, :h_rank;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE wlc; tpabort(0); return 1; }
        rec.pid = h_pid; rec.amt = h_amt; rec.rnk = h_rank;
        if (rec.rnk == 1) {
            EXEC SQL INSERT INTO rc_diff (diff_id, purchase_id, expected_amt, actual_amt, diff_amt, diff_kind, biz_date)
                VALUES (nextval('rc_diff_seq'), :h_pid, :h_amt, :h_amt, 0, 'AMT', :h_bizdate);
            if (sqlca.sqlcode < 0) { EXEC SQL CLOSE wlc; tpabort(0); return 1; }
            loaded++;
        }
    }
    EXEC SQL CLOSE wlc;

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

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