/*
 * st_rerun_batch.pgc - 정산 재실행 배치 (DELETE + INSERT..SELECT + XA).
 * 당일 MDR 정산 상세를 전량 삭제한 뒤 정산-매입 조인으로 매입 fee 기준의
 * MDR 상세를 집합 재생성한다 (정산 재실행). 사용법: st_rerun_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "st_dbio.h"
#include "st_rerun_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    st_rerun_rec_t rec;
    memset(&rec, 0, sizeof(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 DELETE FROM st_settle_dtl WHERE biz_date = :h_bizdate AND fee_type = 'MDR';
    if (sqlca.sqlcode < 0) { fprintf(stderr, "PURGE FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    rec.purged = (long) sqlca.sqlerrd[2];

    EXEC SQL INSERT INTO st_settle_dtl (dtl_id, settlement_id, purchase_id, merchant_id, fee_type, amount, biz_date)
        SELECT nextval('st_dtl_seq'), s.settlement_id, s.purchase_id, s.merchant_id, 'MDR', p.fee, s.biz_date
        FROM settlement s JOIN purchase p ON p.purchase_id = s.purchase_id
        WHERE s.biz_date = :h_bizdate AND s.status <> 'CANCELLED';
    if (sqlca.sqlcode < 0) { fprintf(stderr, "REBUILD FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    rec.rebuilt = (long) sqlca.sqlerrd[2];

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

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