/*
 * mm_close_sweep_batch.pgc - 폐업 가맹점 부속 마스터 정리 배치 (IN-subquery 일괄 + XA).
 *
 * DELETED 가맹점에 딸린 부속 데이터를 일괄 정리한다:
 * 미폐기 단말 SCRAPPED 전환, 수수료율 행 삭제, 한도 행 삭제.
 * 커서 없이 서브쿼리 3방으로 처리. 전 구간 ONE global XA transaction.
 * host 변수는 전용 카피북 mm_close_sweep_cpy.h 를 EXEC SQL INCLUDE.
 * Usage: mm_close_sweep_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_close_sweep_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 UPDATE mm_terminal SET status = 'SCRAPPED'
        WHERE status <> 'SCRAPPED'
          AND merchant_id IN (SELECT merchant_id FROM mm_merchant_ext WHERE status = 'DELETED');
    if (sqlca.sqlcode < 0) { fprintf(stderr, "TERM FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    b_terms = sqlca.sqlerrd[2];

    EXEC SQL DELETE FROM mm_fee_rate
        WHERE merchant_id IN (SELECT merchant_id FROM mm_merchant_ext WHERE status = 'DELETED');
    if (sqlca.sqlcode < 0) { fprintf(stderr, "FEE FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    b_fees = sqlca.sqlerrd[2];

    EXEC SQL DELETE FROM mm_limit
        WHERE merchant_id IN (SELECT merchant_id FROM mm_merchant_ext WHERE status = 'DELETED');
    if (sqlca.sqlcode < 0) { fprintf(stderr, "LIMIT FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    b_limits = sqlca.sqlerrd[2];

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> mm_close_sweep_batch COMMIT: 단말 폐기=%ld 요율 삭제=%ld 한도 삭제=%ld\n",
           b_terms, b_fees, b_limits);

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