/*
 * ac_fxweight_batch.pgc - ac 해외매입 가중 평균 환율 배치 (XA).
 *
 * ATMI client: one global transaction; sums rate_bps weighted by krw_amount and
 * the weight itself, then a C helper computes the weighted average bps.
 * tpcommit drives XA 2PC. Usage: ac_fxweight_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "ac_fxweight_batch.h"

/* 가중합/가중치 나눗셈 (0 보호). */
long acb_fxw_divide(long num, long den)
{
    if (den <= 0) return 0;
    return num / den;
}

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

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_num = 0, h_den = 0;
    EXEC SQL END DECLARE SECTION;

    memset(&ctx, 0, sizeof(ctx));
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    strncpy(ctx.biz_date, bizdate, sizeof(ctx.biz_date)-1);

    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(rate_bps * krw_amount),0), coalesce(sum(krw_amount),0)
        INTO :h_num, :h_den FROM ac_fx WHERE biz_date = :h_bizdate;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "ac_fxweight_batch FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    ctx.num = h_num;
    ctx.den = h_den;
    ctx.avg_bps = acb_fxw_divide(ctx.num, ctx.den);

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> ac_fxweight_batch COMMIT: bizdate=%s weight=%ld avg_bps=%ld\n",
           ctx.biz_date, ctx.den, ctx.avg_bps);

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