/*
 * mm_limit_seed_batch.pgc - 한도 마스터 미보유 가맹점 기본 한도 생성 배치 (커서 + XA).
 *
 * 활성 가맹점 중 mm_limit 행이 없는 건에 대해 기본 한도(일 1억/월 30억/건 1천만)를
 * 생성한다(한도 마스터 정합성 보정). ONE global XA transaction.
 * host 변수는 mm_limit_seed_cpy.h 를 EXEC SQL INCLUDE.
 * Usage: mm_limit_seed_batch
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>

int main(int argc, char **argv)
{
    (void)argc; (void)argv;
    EXEC SQL INCLUDE mm_limit_seed_cpy;
    b_seeded = 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 lsd CURSOR FOR
        SELECT me.merchant_id FROM mm_merchant_ext me
        WHERE me.status = 'ACTIVE'
          AND NOT EXISTS (SELECT 1 FROM mm_limit l WHERE l.merchant_id = me.merchant_id)
        ORDER BY me.merchant_id;
    EXEC SQL OPEN lsd;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH lsd INTO :b_merch;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE lsd; tpabort(0); return 1; }
        EXEC SQL INSERT INTO mm_limit (merchant_id, daily_limit, monthly_limit, per_txn_limit)
            VALUES (:b_merch, 100000000, 3000000000, 10000000);
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE lsd; tpabort(0); return 1; }
        b_seeded++;
    }
    EXEC SQL CLOSE lsd;

    EXEC SQL SELECT count(*) INTO :b_total FROM mm_limit;
    if (sqlca.sqlcode < 0) { tpabort(0); return 1; }

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> mm_limit_seed_batch COMMIT: 신규한도=%ld 전체한도행=%ld\n", b_seeded, b_total);

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