/*
 * cm_rankfx_batch.pgc - cm 기준일 최고환율 랭크 스캔 배치 (XA 단일 글로벌 트랜잭션 배치).
 *
 * ATMI client: tpinit/tpopen open the ECPG XA RM, tpbegin starts ONE global
 * transaction, EXEC SQL runs on the biz_date, then tpcommit drives XA 2PC.
 * Usage: cm_rankfx_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "cm_rankfx_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_ccy[8];
    long h_rn;
    EXEC SQL END DECLARE SECTION;
    cm_rankfx_rec_t rec; rec.scanned = 0; rec.tops = 0;

    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 cra CURSOR FOR
        SELECT ccy,
               ROW_NUMBER() OVER (PARTITION BY base_date ORDER BY rate_bps DESC)
        FROM cm_fx_rate WHERE base_date = :h_bizdate;
    EXEC SQL OPEN cra;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH cra INTO :h_ccy, :h_rn;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE cra; tpabort(0); return 1; }
        rec.scanned++;
        if (h_rn == 1) rec.tops++;
    }
    EXEC SQL CLOSE cra;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> cm_rankfx_batch COMMIT: bizdate=%s 스캔=%ld 최고=%ld\n", bizdate, rec.scanned, rec.tops);

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