/*
 * vl_unacq_batch.pgc - 미매입 승인 검출 배치 (XA 단일 글로벌 트랜잭션 배치).
 *
 * ATMI client: tpinit/tpopen open the ECPG XA RM, tpbegin starts ONE global
 * transaction; 매입 원장이 없는 고아 승인을 집계하고 결과를 검증로그에 남긴 뒤
 * tpcommit drives XA 2PC.
 * Usage: vl_unacq_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "vl_dbio.h"
#include "vl_unacq_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    EXEC SQL BEGIN DECLARE SECTION;
    long h_cnt, h_first;
    EXEC SQL END DECLARE SECTION;
    vl_unacq_rec_t rec;

    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 SELECT count(*), coalesce(min(a.approval_id),0) INTO :h_cnt, :h_first
        FROM approval a
        WHERE NOT EXISTS (SELECT 1 FROM purchase p
                          WHERE p.purchase_id = a.purchase_id);
    if (sqlca.sqlcode < 0) { fprintf(stderr, "vl_unacq_batch FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    if (vldb_insert_check_log(VL_UNACQ_CHECK, h_first, (h_cnt > 0) ? 1 : 0,
                              "미매입 승인 정기 스캔", bizdate) < 0) {
        fprintf(stderr, "vl_unacq_batch 검증로그 적재 FAIL\n"); tpabort(0); return 1;
    }

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    rec.orphans = h_cnt; rec.first_id = h_first;
    printf(">>> vl_unacq_batch COMMIT: bizdate=%s 고아승인=%ld 최초ID=%ld\n",
           bizdate, rec.orphans, rec.first_id);

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