/*
 * ac_limitwatch_batch.pgc - ac 가맹점 한도 임박 감시 배치 (조인 커서, XA).
 *
 * ATMI client: 영업일 사용액을 가맹점 일한도와 조인 집계해 소진율 90%
 * (9000bps)를 넘긴 가맹점을 골라 경고 라인을 출력한다. C 헬퍼가 소진율을
 * bps 로 환산한다.
 * Usage: ac_limitwatch_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "ac_limitwatch_batch.h"

/* 소진율 bps 계산 (한도 0 이면 만점 처리) */
long acb_usage_bps(long used, long limit)
{
    if (limit <= 0) return 10000L;
    return (used * 10000L) / limit;
}

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

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_merch[64];
    long h_used, h_limit;
    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 lwb_cur CURSOR FOR
        SELECT m.merchant_id, coalesce(sum(u.amount), 0), m.daily_limit
        FROM merchant m JOIN purchase u
          ON u.merchant_id = m.merchant_id AND u.biz_date = :h_bizdate
         AND u.status NOT IN ('C', 'V')
        GROUP BY m.merchant_id, m.daily_limit;
    EXEC SQL OPEN lwb_cur;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "open FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH lwb_cur INTO :h_merch, :h_used, :h_limit;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE lwb_cur; fprintf(stderr, "fetch FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }
        cx.scanned++;
        bps = acb_usage_bps(h_used, h_limit);
        if (bps > 9000L) {
            cx.warned++;
            printf("  ** 한도 임박 merchant=%s used=%ld limit=%ld usage=%ld bps\n",
                   h_merch, h_used, h_limit, bps);
        }
    }
    EXEC SQL CLOSE lwb_cur;

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

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