/*
 * vl_promote_batch.pgc - vl 실패 검증로그 의심거래 승격 배치 (XA 단일 글로벌 트랜잭션 배치).
 *
 * ATMI client: tpinit/tpopen open the ECPG XA RM, tpbegin starts ONE global
 * transaction, EXEC SQL runs on the biz_date, then tpcommit drives XA 2PC.
 * Usage: vl_promote_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "vl_promote_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];
    EXEC SQL END DECLARE SECTION;
    vl_promote_rec_t rec;

    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 INSERT INTO vl_suspect
        (suspect_id, purchase_id, rule_code, severity, detail, biz_date)
        SELECT nextval('vl_suspect_seq'), l.target_id, 'CHK_FAIL', 'WARN', l.detail, l.biz_date
        FROM vl_check_log l
        WHERE l.biz_date = :h_bizdate AND l.result_code > 0;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "vl_promote_batch FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    rec.promoted = (long) sqlca.sqlerrd[2];

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> vl_promote_batch COMMIT: bizdate=%s 승격=%ld\n", bizdate, rec.promoted);

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