/*
 * mm_fee_align_batch.pgc - 요율 마스터 미보유 가맹점 기본 요율 생성 배치 (JOIN 커서 + XA).
 *
 * CREDIT 요율(mm_fee_rate)이 없는 활성 가맹점에 대해 base merchant.mdr_bps(없으면 25bps)를
 * 기본 요율로 생성한다(요율 마스터 공백 보정). ONE global XA transaction.
 * host 변수는 mm_fee_align_cpy.h 를 EXEC SQL INCLUDE.
 * Usage: mm_fee_align_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_fee_align_cpy;
    b_aligned = 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 fal CURSOR FOR
        SELECT me.merchant_id, coalesce(m.mdr_bps, 25)
        FROM mm_merchant_ext me
        LEFT JOIN merchant m ON m.merchant_id = me.merchant_id
        WHERE me.status = 'ACTIVE'
          AND NOT EXISTS (SELECT 1 FROM mm_fee_rate f
                          WHERE f.merchant_id = me.merchant_id AND f.card_type = 'CREDIT')
        ORDER BY me.merchant_id;
    EXEC SQL OPEN fal;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH fal INTO :b_merch, :b_bps;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE fal; tpabort(0); return 1; }
        EXEC SQL INSERT INTO mm_fee_rate (merchant_id, card_type, rate_bps)
            VALUES (:b_merch, 'CREDIT', :b_bps);
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE fal; tpabort(0); return 1; }
        b_aligned++;
    }
    EXEC SQL CLOSE fal;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> mm_fee_align_batch COMMIT: 기본요율 생성=%ld건\n", b_aligned);

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