/*
 * st_promo_batch.pgc - 프로모션/이벤트 정산 배치 (집합 INSERT..SELECT + XA).
 * 당일 거래대금이 기준액 이상인 가맹점 집계에 대해 수수료의 10% 를 이벤트
 * 환급 조정(PROMO)으로 일괄 생성한다. 사용법: st_promo_batch [YYYY-MM-DD] [threshold]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "st_dbio.h"
#include "st_promo_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    st_promo_rec_t rec;
    rec.threshold = (argc > 2) ? atol(argv[2]) : ST_PROMO_DEF_THRESH;
    rec.granted = 0;

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_thr;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    h_thr = rec.threshold;

    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 st_adjust (adj_id, settlement_id, purchase_id, delta, reason, biz_date)
        SELECT nextval('st_adj_seq'), 0, 0, fee_amount / 10, 'PROMO', biz_date
        FROM st_merch_settle
        WHERE biz_date = :h_bizdate AND gross_amount >= :h_thr AND fee_amount > 0;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "%s FAIL [%d] %s\n", ST_PROMO_TAG, sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    rec.granted = (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 threshold=%ld promo_granted=%ld\n", ST_PROMO_TAG, bizdate, rec.threshold, rec.granted);

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