/*
 * mm_bin_dedup_batch.pgc - mm 비활성 BIN 정리 배치 (DELETE range + XA).
 *
 * 지정 카드브랜드의 비활성(status<>'ACTIVE') BIN 행을 한 문장으로 삭제하고
 * 삭제행수를 sqlca.sqlerrd[2] 로 확인한다. ONE global XA transaction.
 * host 변수는 전용 카피북 mm_bin_dedup_cpy.h 를 EXEC SQL INCLUDE.
 * Usage: mm_bin_dedup_batch [CARD_BRAND]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>

int main(int argc, char **argv)
{
    const char *brand = (argc > 1) ? argv[1] : "LOCAL";

    EXEC SQL INCLUDE mm_bin_dedup_cpy;

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

    EXEC SQL DELETE FROM mm_bin WHERE card_brand = :d_brand AND status <> 'ACTIVE';
    if (sqlca.sqlcode < 0) { fprintf(stderr, "DELETE FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    d_deleted = (long) sqlca.sqlerrd[2];

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> mm_bin_dedup_batch COMMIT: brand=%s 삭제=%ld건\n", brand, d_deleted);

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