/*
 * mm_hist_archive_batch.pgc - mm 현행 수수료율 이력 적재 배치 (INSERT..SELECT + XA).
 *
 * 현재 mm_fee_rate 스냅샷 전체를 mm_fee_rate_hist 에 한 문장으로 적재한다.
 * hist_id 는 시퀀스 기준값 + row_number() 로 부여. ONE global XA transaction.
 * host 변수는 전용 카피북 mm_hist_archive_cpy.h 를 EXEC SQL INCLUDE.
 * Usage: mm_hist_archive_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_hist_archive_cpy;

    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 SELECT coalesce(max(hist_id),0) INTO :a_base FROM mm_fee_rate_hist;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "BASE FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    EXEC SQL INSERT INTO mm_fee_rate_hist (hist_id, merchant_id, card_type, rate_bps, eff_date)
        SELECT :a_base + row_number() OVER (ORDER BY merchant_id, card_type),
               merchant_id, card_type, rate_bps, eff_date
        FROM mm_fee_rate;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "INSERT FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    a_rows = (long) sqlca.sqlerrd[2];

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> mm_hist_archive_batch COMMIT: 이력적재=%ld건\n", a_rows);

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