/*
 * cm_fxjoin_batch.pgc - cm 환율 x 통화코드 조인 집계 배치 (XA).
 *
 * ATMI client: tpinit/tpopen open the ECPG XA RM, tpbegin starts ONE global
 * transaction; cm_fx_rate 를 cm_code(CCY 그룹)와 조인하여 등록 통화의 환율
 * 합계와 고유 통화 수(count DISTINCT)를 한 행으로 집계; then tpcommit.
 * Usage: cm_fxjoin_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "cm_dbio.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];
    long h_sum = 0, h_ccy = 0;
    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 coalesce(sum(r.rate_bps),0), count(DISTINCT r.ccy)
        INTO :h_sum, :h_ccy
        FROM cm_fx_rate r JOIN cm_code c ON r.ccy = c.code
        WHERE r.base_date = :h_bizdate AND c.code_grp = 'CCY';
    if (sqlca.sqlcode < 0) { fprintf(stderr, "cm_fxjoin_batch 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(">>> cm_fxjoin_batch COMMIT: bizdate=%s rate_sum=%ld ccy=%ld\n", bizdate, h_sum, h_ccy);

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