/*
 * vl_dupappr_batch.pgc - 중복 승인 스캔 배치 (XA).
 *
 * ATMI client: tpinit/tpopen open the ECPG XA RM, tpbegin starts ONE global
 * transaction; the 검증 SELECT/집계 runs on that branch, then tpcommit drives XA 2PC.
 * Usage: vl_dupappr_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "vl_dbio.h"
#include "vl_dupappr_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_dupappr_rec_t rec; rec.groups = 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 dac CURSOR FOR
        SELECT purchase_id, count(*) FROM approval
        WHERE approved = true GROUP BY purchase_id HAVING count(*) > 1;
    EXEC SQL OPEN dac;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH dac INTO :h_pid, :h_cnt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE dac; tpabort(0); return 1; }
        if (vldb_insert_suspect(h_pid, VL_DUPAPPR_RULE, "WARN", "중복 승인 의심", h_bizdate) < 0) {
            EXEC SQL CLOSE dac; tpabort(0); return 1;
        }
        rec.groups++;
    }
    EXEC SQL CLOSE dac;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "vl_dupappr_batch FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> vl_dupappr_batch COMMIT: bizdate=%s 중복승인그룹=%ld\n", bizdate, rec.groups);

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