/*
 * st_approve_batch.pgc - 정산 승인 워크플로 배치 (2단 검증 + 집합 승격 + XA).
 * 당일 CONFIRMED 정산을 확인한 뒤 net>0 건만 APPROVED 로 일괄 승격하고,
 * 승인 대상에서 빠진 건수(net<=0)를 별도 집계한다. 승인 원장 마커 기록.
 * 사용법: st_approve_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "st_dbio.h"
#include "st_approve_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    st_approve_rec_t rec;
    memset(&rec, 0, sizeof(rec));
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_confirmed;
    EXEC SQL END DECLARE SECTION;
    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 SELECT count(*) INTO :h_confirmed FROM settlement
        WHERE biz_date = :h_bizdate AND status = 'CONFIRMED';
    if (sqlca.sqlcode < 0) { fprintf(stderr, "CHECK FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    EXEC SQL UPDATE settlement SET status = 'APPROVED'
        WHERE biz_date = :h_bizdate AND status = 'CONFIRMED' AND net > 0;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "APPROVE FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    rec.approved = (long) sqlca.sqlerrd[2];
    rec.skipped = h_confirmed - rec.approved;

    EXEC SQL INSERT INTO ledger (ledger_id, purchase_id, entry_type, amount, biz_date)
        VALUES (nextval('ledger_seq'), 0, 'STAPPROVE', :h_confirmed, :h_bizdate);
    if (sqlca.sqlcode < 0) { fprintf(stderr, "MARKER 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(">>> %s COMMIT: bizdate=%s approved=%ld skipped=%ld\n", ST_APPROVE_TAG, bizdate, rec.approved, rec.skipped);

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