/*
 * ac_summaryrebuild_batch.pgc - ac 가맹점 일집계 재구축 배치 (INSERT..SELECT + upsert + XA).
 *
 * ATMI client: one global transaction; an INSERT..SELECT..GROUP BY re-aggregates
 * purchase into merchant_summary via ON CONFLICT DO UPDATE, then reads back the
 * rebuilt gross. tpcommit drives XA 2PC. Usage: ac_summaryrebuild_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "ac_summaryrebuild_batch.h"

/* 반영 행수가 음수가 아니면 그대로 반환. */
long acb_rebuild_ok(long affected)
{
    return (affected < 0) ? 0 : affected;
}

int main(int argc, char **argv)
{
    ac_rebuild_ctx_t ctx;
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_gross = 0;
    EXEC SQL END DECLARE SECTION;

    memset(&ctx, 0, sizeof(ctx));
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    strncpy(ctx.biz_date, bizdate, sizeof(ctx.biz_date)-1);

    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 merchant_summary
        (merchant_id, biz_date, txn_count, gross_amount, fee_amount, net_amount)
        SELECT merchant_id, biz_date, count(*), coalesce(sum(amount),0),
               coalesce(sum(fee),0), coalesce(sum(net),0)
        FROM purchase WHERE biz_date = :h_bizdate
        GROUP BY merchant_id, biz_date
        ON CONFLICT (merchant_id, biz_date) DO UPDATE
        SET txn_count = EXCLUDED.txn_count,
            gross_amount = EXCLUDED.gross_amount,
            fee_amount = EXCLUDED.fee_amount,
            net_amount = EXCLUDED.net_amount,
            updated_at = now();
    if (sqlca.sqlcode < 0) { fprintf(stderr, "ac_summaryrebuild_batch FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    ctx.rows_affected = acb_rebuild_ok(sqlca.sqlerrd[2]);

    EXEC SQL SELECT coalesce(sum(gross_amount),0) INTO :h_gross FROM merchant_summary WHERE biz_date = :h_bizdate;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "ac_summaryrebuild_batch READ FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    ctx.total_gross = h_gross;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> ac_summaryrebuild_batch COMMIT: bizdate=%s rows=%ld gross=%ld\n",
           ctx.biz_date, ctx.rows_affected, ctx.total_gross);

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