/*
 * au_approverate_batch.pgc - au 일일 승인율 배치 (FILTER 집계 + XA).
 *
 * ATMI client: one global transaction; a FILTER aggregate counts approved vs.
 * total authorizations, then a C helper computes the approval rate in bps.
 * tpcommit drives XA 2PC. Usage: au_approverate_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "au_approverate_batch.h"

/* 승인율(bps) = approved/total * 10000. total<=0 이면 0. */
long aub_rate_bps(long approved, long total)
{
    if (total <= 0) return 0;
    return (approved * 10000L) / total;
}

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

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_appr = 0, h_total = 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 count(*) FILTER (WHERE status = 'A'), count(*)
        INTO :h_appr, :h_total FROM au_authorization WHERE biz_date = :h_bizdate;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "au_approverate_batch FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    ctx.approved = h_appr;
    ctx.total = h_total;
    ctx.rate_bps = aub_rate_bps(ctx.approved, ctx.total);

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

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