/*
 * mm_acct_scan_batch.pgc - 정산계좌 형식 점검 배치 (커서 + C 검증 + XA).
 *
 * 활성 가맹점의 정산계좌를 순회하며 C 코드로 숫자 10~16자리 형식을 검증하고
 * 위반 건에 ACCT_BAD 이력을 남긴다(정산 오류 예방). ONE global XA transaction.
 * host 변수는 mm_acct_scan_cpy.h 를 EXEC SQL INCLUDE.
 * Usage: mm_acct_scan_batch
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "mm_dbio.h"

static int acct_bad(const char *a)
{
    size_t i, len = strlen(a);
    if (len < 10 || len > 16) return 1;
    for (i = 0; i < len; i++)
        if (a[i] < '0' || a[i] > '9') return 1;
    return 0;
}

int main(int argc, char **argv)
{
    (void)argc; (void)argv;
    EXEC SQL INCLUDE mm_acct_scan_cpy;
    b_bad = 0; b_scanned = 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 acsn CURSOR FOR
        SELECT merchant_id, settle_acct FROM mm_merchant_ext
        WHERE status = 'ACTIVE' AND settle_acct <> ''
        ORDER BY merchant_id;
    EXEC SQL OPEN acsn;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH acsn INTO :b_merch, :b_acct;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE acsn; tpabort(0); return 1; }
        b_scanned++;
        if (!acct_bad(b_acct)) continue;
        if (mmdb_insert_merch_hist(b_merch, "ACCT_BAD", b_acct, "FORMAT", "배치 계좌 형식 위반") < 0) {
            EXEC SQL CLOSE acsn; tpabort(0); return 1;
        }
        b_bad++;
    }
    EXEC SQL CLOSE acsn;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> mm_acct_scan_batch COMMIT: 점검=%ld 위반=%ld건\n", b_scanned, b_bad);

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