/*
 * rc_orphan_batch.pgc - 고아 매입 검출 배치 (XA).
 * 승인(approval)이 없는 당일 매입을 두 갈래로 일괄 적재한다: (1) 미매입
 * 관리(ac_unmatch), (2) 대사 예외(rc_exception). 두 INSERT..SELECT 가 한
 * 글로벌 트랜잭션으로 묶여 2PC 커밋된다.
 * 사용법: rc_orphan_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "rc_dbio.h"
#include "rc_orphan_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    rc_orphan_rec_t rec;

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    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 INSERT INTO ac_unmatch (unmatch_id, purchase_id, reason, biz_date)
        SELECT nextval('ac_unmatch_seq'), p.purchase_id, 'NO APPROVAL', p.biz_date
        FROM purchase p
        WHERE p.biz_date = :h_bizdate
          AND NOT EXISTS (SELECT 1 FROM approval a WHERE a.purchase_id = p.purchase_id);
    if (sqlca.sqlcode < 0) { fprintf(stderr, "%s INSERT unmatch FAIL [%d] %s\n", RC_ORPHAN_TAG, sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    rec.unmatch_rows = sqlca.sqlerrd[2];

    EXEC SQL INSERT INTO rc_exception (exc_id, purchase_id, reason, biz_date)
        SELECT nextval('rc_exc_seq'), p.purchase_id, 'ORPHAN PURCHASE', p.biz_date
        FROM purchase p
        WHERE p.biz_date = :h_bizdate
          AND NOT EXISTS (SELECT 1 FROM approval a WHERE a.purchase_id = p.purchase_id)
          AND NOT EXISTS (SELECT 1 FROM rc_exception e
                          WHERE e.purchase_id = p.purchase_id AND e.resolved = false);
    if (sqlca.sqlcode < 0) { fprintf(stderr, "%s INSERT exc FAIL [%d] %s\n", RC_ORPHAN_TAG, sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    rec.exc_rows = sqlca.sqlerrd[2];

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> %s COMMIT: bizdate=%s unmatch=%ld exceptions=%ld\n",
           RC_ORPHAN_TAG, bizdate, rec.unmatch_rows, rec.exc_rows);

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