/*
 * rc_carryover_batch.pgc - 이월 대사 배치 (XA).
 * 전일 EXCEPTION 대사 건을 익일 HOLD 건으로 INSERT..SELECT 일괄 이월하고,
 * 이월 원본 예외는 resolved 처리하여 이중 이월을 막는다.
 * 사용법: rc_carryover_batch [FROM-YYYY-MM-DD] [TO-YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "rc_dbio.h"
#include "rc_carryover_batch.h"

int main(int argc, char **argv)
{
    rc_carryover_rec_t rec;
    EXEC SQL BEGIN DECLARE SECTION;
    char h_from[16], h_to[16];
    long h_resolved;
    EXEC SQL END DECLARE SECTION;

    strncpy(rec.from_date, (argc > 1) ? argv[1] : "2026-07-19", sizeof(rec.from_date)-1);
    rec.from_date[sizeof(rec.from_date)-1] = 0;
    strncpy(rec.to_date, (argc > 2) ? argv[2] : "2026-07-20", sizeof(rec.to_date)-1);
    rec.to_date[sizeof(rec.to_date)-1] = 0;
    strcpy(h_from, rec.from_date);
    strcpy(h_to, rec.to_date);

    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'), purchase_id, 'CARRY', amount, 'HOLD', CAST(:h_to AS date)
        FROM rc_match_log WHERE biz_date = :h_from AND status = 'EXCEPTION';
    if (sqlca.sqlcode < 0) { fprintf(stderr, "%s INSERT FAIL [%d] %s\n", RC_CARRYOVER_TAG, sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    rec.carried = sqlca.sqlerrd[2];

    EXEC SQL UPDATE rc_exception SET resolved = true
        WHERE biz_date = :h_from AND resolved = false;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "%s UPDATE FAIL [%d] %s\n", RC_CARRYOVER_TAG, sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    h_resolved = sqlca.sqlerrd[2];

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> %s COMMIT: %s -> %s carried=%ld resolved=%ld\n",
           RC_CARRYOVER_TAG, rec.from_date, rec.to_date, rec.carried, h_resolved);

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