/*
 * cm_fxcross_batch.pgc - cm 교차환율 산출 배치 (XA).
 *
 * 기준일 고시된 통화들을 커서로 훑어 기준통화(USD) 대비 교차환율(1e6 스케일)을
 * 산출하고, 가장 큰 교차율을 추적한다. 기준통화 자체 고시가 없으면 조용히
 * 종료(종료코드 2). 요약을 svc=FXCROSS 로그로 남긴다.
 * Usage: cm_fxcross_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "cm_fxcross_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    cm_fxcross_rec_t rec = { 0, 0, 0 };
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_ccy[8], h_base[8], h_msg[112];
    long h_rate, h_base_rate;
    EXEC SQL END DECLARE SECTION;

    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    strcpy(h_base, CM_FXCROSS_BASE);

    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 rate_bps INTO :h_base_rate FROM cm_fx_rate
        WHERE ccy = :h_base AND base_date = :h_bizdate;
    if (sqlca.sqlcode == 100) { tpabort(0);
        printf(">>> cm_fxcross_batch: 기준통화 %s 미고시\n", h_base); tpterm(); return 2; }
    if (sqlca.sqlcode < 0) { tpabort(0); return 1; }
    rec.base_rate = h_base_rate;

    EXEC SQL DECLARE cur_fc CURSOR FOR
        SELECT ccy, rate_bps FROM cm_fx_rate
        WHERE base_date = :h_bizdate AND ccy <> :h_base ORDER BY ccy;
    EXEC SQL OPEN cur_fc;
    if (sqlca.sqlcode < 0) { tpabort(0); return 1; }

    for (;;) {
        long cross;
        EXEC SQL FETCH cur_fc INTO :h_ccy, :h_rate;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE cur_fc; tpabort(0); return 1; }
        if (h_rate <= 0) continue;
        cross = h_base_rate * 1000000L / h_rate;     /* USD 1단위당 대상통화 */
        if (cross > rec.max_cross) rec.max_cross = cross;
        rec.pairs++;
    }
    EXEC SQL CLOSE cur_fc;

    snprintf(h_msg, sizeof(h_msg), "FXCROSS base=%s pairs=%ld maxcross=%ld",
             h_base, rec.pairs, rec.max_cross);
    EXEC SQL INSERT INTO cm_log (log_id, svc_name, log_level, msg, biz_date)
        VALUES (nextval('cm_log_seq'), 'FXCROSS', 'I', :h_msg, :h_bizdate);
    if (sqlca.sqlcode < 0) { tpabort(0); return 1; }

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> cm_fxcross_batch COMMIT: 통화쌍=%ld 최대교차=%ld\n", rec.pairs, rec.max_cross);

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