/*
 * vl_duppay_batch.pgc - 중복지급 스캔 배치 (XA 단일 글로벌 트랜잭션 배치).
 *
 * ATMI client: tpinit/tpopen open the ECPG XA RM, tpbegin starts ONE global
 * transaction; 커서로 지급(XFER) 원장이 2건 이상인 매입을 훑어 의심거래로
 * 적재한 뒤 tpcommit drives XA 2PC.
 * Usage: vl_duppay_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "vl_dbio.h"
#include "vl_duppay_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_pid, h_cnt;
    EXEC SQL END DECLARE SECTION;
    vl_duppay_rec_t rec; rec.dup_groups = 0; rec.suspects = 0;

    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-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 DECLARE vdpc CURSOR FOR
        SELECT purchase_id, count(*) FROM ledger
        WHERE biz_date = :h_bizdate AND entry_type = 'XFER'
        GROUP BY purchase_id HAVING count(*) > 1;
    EXEC SQL OPEN vdpc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "vl_duppay_batch OPEN FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH vdpc INTO :h_pid, :h_cnt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "vl_duppay_batch FETCH FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }
        rec.dup_groups++;
        if (vldb_insert_suspect(h_pid, VL_DUPPAY_RULE, VL_DUPPAY_SEV,
                                "지급 원장 중복 기표", h_bizdate) < 0) {
            fprintf(stderr, "vl_duppay_batch 의심거래 적재 FAIL\n"); tpabort(0); return 1;
        }
        rec.suspects++;
    }
    EXEC SQL CLOSE vdpc;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> vl_duppay_batch COMMIT: bizdate=%s 중복지급그룹=%ld 의심거래적재=%ld\n",
           bizdate, rec.dup_groups, rec.suspects);

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