/*
 * mm_fee_bump_batch.pgc - mm 수수료율 일괄 인상 배치 (커서 + UPDATE + XA).
 *
 * 지정 card_type 의 수수료율 행을 커서로 훑어 rate_bps 를 delta 만큼 인상하고,
 * 변경 이력을 mm_fee_rate_hist 에 남긴다. 전 구간 ONE global XA transaction.
 * host 변수는 전용 카피북 mm_fee_bump_cpy.h 를 EXEC SQL INCLUDE.
 * Usage: mm_fee_bump_batch [CARD_TYPE] [DELTA_BPS]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>

int main(int argc, char **argv)
{
    const char *card = (argc > 1) ? argv[1] : "CREDIT";
    long delta = (argc > 2) ? atol(argv[2]) : 1;
    long bumped = 0;

    EXEC SQL INCLUDE mm_fee_bump_cpy;

    strncpy(b_card, card, sizeof(b_card)-1); b_card[sizeof(b_card)-1] = 0;
    b_delta = delta;

    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 mfb CURSOR FOR
        SELECT merchant_id FROM mm_fee_rate WHERE card_type = :b_card ORDER BY merchant_id;
    EXEC SQL OPEN mfb;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH mfb INTO :b_merch;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE mfb; tpabort(0); return 1; }
        EXEC SQL UPDATE mm_fee_rate SET rate_bps = rate_bps + :b_delta, updated_at = now()
            WHERE merchant_id = :b_merch AND card_type = :b_card;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "UPDATE FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE mfb; tpabort(0); return 1; }
        bumped++;
    }
    EXEC SQL CLOSE mfb;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> mm_fee_bump_batch COMMIT: card=%s delta=%ld 인상=%ld건\n", card, delta, bumped);

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