/*
 * ac_ccysum_batch.pgc - ac 통화별 해외매입 집계 배치 (통화 커서, XA).
 *
 * ATMI client: 영업일 해외매입 원장을 통화별로 그룹 집계해 통화마다
 * 건수/원통화합계/원화환산합계/평균환율을 한 줄씩 출력한다.
 * Usage: ac_ccysum_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "ac_ccysum_batch.h"

int main(int argc, char **argv)
{
    ac_ccysum_ctx_t cx;
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_ccy[8];
    long h_n, h_fx, h_krw, h_rate;
    EXEC SQL END DECLARE SECTION;

    memset(&cx, 0, sizeof(cx));
    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 ccb_cur CURSOR FOR
        SELECT ccy, count(*), sum(fx_amount), sum(krw_amount), avg(rate_bps)::bigint
        FROM ac_fx WHERE biz_date = :h_bizdate
        GROUP BY ccy ORDER BY sum(krw_amount) DESC;
    EXEC SQL OPEN ccb_cur;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "open FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH ccb_cur INTO :h_ccy, :h_n, :h_fx, :h_krw, :h_rate;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE ccb_cur; fprintf(stderr, "fetch FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }
        printf("  ccy=%-4s n=%ld fx=%ld krw=%ld avg_rate=%ld\n", h_ccy, h_n, h_fx, h_krw, h_rate);
        cx.ccy_kinds++;
        cx.krw_total += h_krw;
    }
    EXEC SQL CLOSE ccb_cur;

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

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