/*
 * rc_retro_batch.pgc - 소급 대사 배치 (XA).
 * 과거 영업일에 EXCEPTION 으로 남은 대사 건들을 새 영업일 HOLD 상태로 소급
 * 이동(UPDATE)시키고, 소급 처리 사실을 INFO 경보로 남긴다.
 * 사용법: rc_retro_batch [OLD-YYYY-MM-DD] [NEW-YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "rc_dbio.h"
#include "rc_retro_batch.h"

int main(int argc, char **argv)
{
    rc_retro_rec_t rec;
    EXEC SQL BEGIN DECLARE SECTION;
    char h_old[16], h_new[16], h_msg[96];
    EXEC SQL END DECLARE SECTION;

    strncpy(rec.old_day, (argc > 1) ? argv[1] : "2026-07-18", sizeof(rec.old_day)-1);
    rec.old_day[sizeof(rec.old_day)-1] = 0;
    strncpy(rec.new_day, (argc > 2) ? argv[2] : "2026-07-19", sizeof(rec.new_day)-1);
    rec.new_day[sizeof(rec.new_day)-1] = 0;
    strcpy(h_old, rec.old_day);
    strcpy(h_new, rec.new_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 UPDATE rc_match_log
        SET biz_date = CAST(:h_new AS date), status = 'HOLD', updated_at = now()
        WHERE biz_date = :h_old AND status = 'EXCEPTION';
    if (sqlca.sqlcode < 0) { fprintf(stderr, "%s UPDATE FAIL [%d] %s\n", RC_RETRO_TAG, sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    rec.moved = sqlca.sqlerrd[2];

    if (rec.moved > 0) {
        snprintf(h_msg, sizeof(h_msg), "retro recon %.12s -> %.12s rows=%ld",
                 rec.old_day, rec.new_day, rec.moved);
        EXEC SQL INSERT INTO rc_alert (alert_id, purchase_id, lvl, message, biz_date)
            VALUES (nextval('rc_alert_seq'), 0, 'INFO', :h_msg, :h_new);
        if (sqlca.sqlcode < 0) { tpabort(0); return 1; }
    }

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> %s COMMIT: %s -> %s moved=%ld\n", RC_RETRO_TAG, rec.old_day, rec.new_day, rec.moved);

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