/*
 * au_summary_build_batch.pgc - au 가맹점 승인 일집계 생성 (INSERT..SELECT, XA).
 *
 * Rolls the day's au_authorization rows up per merchant and INSERTs them into
 * au_summary in a single set-based statement (ON CONFLICT merge), all under ONE
 * global XA transaction. Usage: au_summary_build_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "au_dbio.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    long 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 au_summary
        (merchant_id, biz_date, auth_count, approve_count, decline_count, auth_amount)
        SELECT merchant_id, :h_bizdate, 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
        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_summary_build_batch FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    rows = sqlca.sqlerrd[2];

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> au_summary_build_batch COMMIT: bizdate=%s merchants=%ld\n", bizdate, rows);

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