/*
 * st_chargeback_batch.pgc - 차지백 회수 정산 배치 (XA 배치).
 * 당일 정산 조정 중 차지백(reason=CHARGEBACK) 건을 집계해 회수 규모를 산출하고,
 * 당일 지급 예정(SCHEDULED)을 일괄 보류(HELD)로 전환해 회수 대상을 잠근다.
 * 사용법: st_chargeback_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "st_dbio.h"
#include "st_chargeback_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    st_chargeback_rec_t rec;
    memset(&rec, 0, sizeof(rec));
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_cnt, h_sum;
    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 SELECT count(*), coalesce(sum(delta),0) INTO :h_cnt, :h_sum
        FROM st_adjust WHERE biz_date = :h_bizdate AND reason = 'CHARGEBACK';
    if (sqlca.sqlcode < 0) { fprintf(stderr, "SUM FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }
    rec.cb_cnt = h_cnt; rec.cb_total = h_sum;

    if (h_cnt > 0) {
        EXEC SQL UPDATE st_payment SET status = 'HELD'
            WHERE biz_date = :h_bizdate AND status = 'SCHEDULED';
        if (sqlca.sqlcode < 0) { fprintf(stderr, "UPD FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }
        rec.held_upd = sqlca.sqlerrd[2];
    }

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> %s COMMIT: bizdate=%s cb_cnt=%ld cb_total=%ld held_upd=%ld\n",
           ST_CHARGEBACK_TAG, bizdate, rec.cb_cnt, rec.cb_total, rec.held_upd);
    tpclose(); tpterm();
    return 0;
}
