/*
 * st_adjnet_batch.pgc - st 가맹점 조정 순액 백필 (INSERT..SELECT upsert + XA).
 *
 * st_adjust 를 가맹점 기준이 아닌 정산건 기준으로 집계하기 어려우므로, 지급(st_payment)
 * 가맹점별 조정 총액을 st_merch_settle 순액에 반영하는 INSERT..SELECT upsert 를 수행.
 * 사용법: st_adjnet_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "st_dbio.h"
#include "st_adjnet_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    st_adjnet_rec_t rec; rec.rows = 0;

    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 INSERT INTO st_merch_settle (merchant_id, biz_date, txn_count, gross_amount, fee_amount, net_amount)
        SELECT merchant_id, biz_date, count(*), coalesce(sum(net_amount), 0), 0, coalesce(sum(net_amount), 0)
        FROM st_payment WHERE biz_date = :h_bizdate GROUP BY merchant_id, biz_date
        ON CONFLICT (merchant_id, biz_date) DO UPDATE
        SET net_amount = st_merch_settle.net_amount + EXCLUDED.net_amount, updated_at = now();
    if (sqlca.sqlcode < 0) { fprintf(stderr, "INSERT..SELECT FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    rec.rows = (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 upserted=%ld\n", ST_ADJNET_TAG, bizdate, rec.rows);

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