/*
 * mm_acct_reverify_batch.pgc - 정산계좌 정기 재검증 배치 (전수 검증 이력 적재 + XA).
 *
 * 활성 가맹점의 정산계좌를 커서로 전수 재검증하여 결과(OK/EMPTY/FORMAT)를
 * 가맹점별 ACCT_VRF 검증 이력으로 남긴다 (온라인 MM_ACCT_VERIFY 와 동일 판정 기준).
 * 전 구간 ONE global XA transaction.
 * host 변수는 전용 카피북 mm_acct_reverify_cpy.h 를 EXEC SQL INCLUDE.
 * Usage: mm_acct_reverify_batch
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "mm_dbio.h"

static const char *acct_verdict(const char *acct)
{
    size_t i, len = strlen(acct);
    if (len == 0) return "EMPTY";
    if (len < 10 || len > 16) return "FORMAT";
    for (i = 0; i < len; i++)
        if (acct[i] < '0' || acct[i] > '9') return "FORMAT";
    return "OK";
}

int main(int argc, char **argv)
{
    long total = 0, failed = 0;
    const char *result;
    (void)argc; (void)argv;

    EXEC SQL INCLUDE mm_acct_reverify_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 DECLARE arv CURSOR FOR
        SELECT merchant_id, settle_acct FROM mm_merchant_ext
        WHERE status = 'ACTIVE'
        ORDER BY merchant_id;
    EXEC SQL OPEN arv;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH arv INTO :b_merch, :b_acct;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE arv; tpabort(0); return 1; }
        result = acct_verdict(b_acct);
        if (mmdb_insert_merch_hist(b_merch, "ACCT_VRF", "", result, "정기 배치 재검증") < 0) {
            EXEC SQL CLOSE arv; tpabort(0); return 1;
        }
        total++;
        if (strcmp(result, "OK") != 0) failed++;
    }
    EXEC SQL CLOSE arv;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> mm_acct_reverify_batch COMMIT: 재검증=%ld건 불량=%ld건\n", total, failed);

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