/*
 * py_limitguard_batch.pgc - py 지급한도 초과 자동 보류 배치 (HAVING 커서 + UPDATE, XA).
 *
 * 당일 확정성 지급(A/F/P) 합계가 일한도(merchant.daily_limit)를 넘긴 가맹점을
 * GROUP BY ... HAVING 커서로 뽑아, 초과액과 함께 잔여 요청(R)건을 보류시킨다.
 * host 변수는 전용 카피북 py_limitguard_cpy.h 를 EXEC SQL INCLUDE.
 * Usage: py_limitguard_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>

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

    EXEC SQL INCLUDE py_limitguard_cpy;

    strncpy(c_bizdate, bizdate, sizeof(c_bizdate)-1); c_bizdate[sizeof(c_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(90, 0) < 0) { fprintf(stderr, "tpbegin FAIL: %s\n", tpstrerror(tperrno)); return 1; }

    EXEC SQL DECLARE plg CURSOR FOR
        SELECT m.merchant_id, coalesce(sum(p.net),0) - m.daily_limit
          FROM py_payout p JOIN merchant m ON p.merchant_id = m.merchant_id
         WHERE p.biz_date = :c_bizdate AND p.status IN ('A','F','P')
         GROUP BY m.merchant_id, m.daily_limit
        HAVING coalesce(sum(p.net),0) > m.daily_limit;
    EXEC SQL OPEN plg;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH plg INTO :c_merch, :c_over;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE plg; tpabort(0); return 1; }
        over_merchants++;
        EXEC SQL UPDATE py_payout SET status = 'H', reject_reason = '한도초과', updated_at = now()
            WHERE merchant_id = :c_merch AND biz_date = :c_bizdate AND status = 'R';
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE plg; tpabort(0); return 1; }
        held += sqlca.sqlerrd[2];
        printf("  [한도초과] %s: 초과액=%ld 보류=%ld건\n", c_merch, c_over, sqlca.sqlerrd[2]);
    }
    EXEC SQL CLOSE plg;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> py_limitguard_batch COMMIT: bizdate=%s 초과가맹점=%ld 보류=%ld건\n", bizdate, over_merchants, held);

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