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

/* 음수 반영행수는 0 으로 클립. */
long aub_rebuild_clip(long affected)
{
    return (affected < 0) ? 0 : affected;
}

int main(int argc, char **argv)
{
    au_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_appr = 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 au_summary
        (merchant_id, biz_date, auth_count, approve_count, decline_count, auth_amount)
        SELECT merchant_id, biz_date, count(*),
               count(*) FILTER (WHERE status = 'A'),
               count(*) FILTER (WHERE status = 'D'),
               coalesce(sum(amount),0)
        FROM au_authorization WHERE biz_date = :h_bizdate
        GROUP BY merchant_id, biz_date
        ON CONFLICT (merchant_id, biz_date) DO UPDATE
        SET auth_count = EXCLUDED.auth_count,
            approve_count = EXCLUDED.approve_count,
            decline_count = EXCLUDED.decline_count,
            auth_amount = EXCLUDED.auth_amount,
            updated_at = now();
    if (sqlca.sqlcode < 0) { fprintf(stderr, "au_summaryrebuild_batch FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    ctx.rows_affected = aub_rebuild_clip(sqlca.sqlerrd[2]);

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

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

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