/*
 * rc_cancelrec_batch.pgc - 취소분 대사 배치 (XA).
 * 당일 취소 증빙(ac_cancel)이 존재하는 매입 중 아직 CANCEL 대사 로그가 없는
 * 건을 INSERT..SELECT 한 방으로 MATCHED 대사 처리한다 (중복 대사 방지).
 * 사용법: rc_cancelrec_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "rc_dbio.h"
#include "rc_cancelrec_batch.h"

int main(int argc, char **argv)
{
    rc_cancelrec_rec_t rec;
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    EXEC SQL END DECLARE SECTION;

    strncpy(rec.day, (argc > 1) ? argv[1] : "2026-07-19", sizeof(rec.day)-1);
    rec.day[sizeof(rec.day)-1] = 0;
    strcpy(h_bizdate, rec.day);

    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 rc_match_log (match_id, purchase_id, match_type, amount, status, biz_date)
        SELECT nextval('rc_match_seq'), p.purchase_id, 'CANCEL', p.amount, 'MATCHED', p.biz_date
        FROM purchase p
        WHERE p.biz_date = :h_bizdate
          AND EXISTS (SELECT 1 FROM ac_cancel c WHERE c.purchase_id = p.purchase_id)
          AND NOT EXISTS (SELECT 1 FROM rc_match_log r
                          WHERE r.purchase_id = p.purchase_id AND r.match_type = 'CANCEL');
    if (sqlca.sqlcode < 0) { fprintf(stderr, "%s INSERT FAIL [%d] %s\n", RC_CANCELREC_TAG, sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    rec.matched = sqlca.sqlerrd[2];

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

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