/*
 * py_winrank_batch.pgc - py 누계 최고점 (윈도우 함수 배치, XA).
 *
 * Computes the peak per-merchant running total of net payouts for the day using
 * a SUM() OVER window, inside ONE XA transaction.
 * Usage: py_winrank_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "py_winrank_batch.h"

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

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_peak;
    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 SELECT coalesce(max(run_tot),0) INTO :h_peak FROM (
        SELECT sum(net) OVER (PARTITION BY merchant_id ORDER BY payout_id) AS run_tot
        FROM py_payout WHERE biz_date = :h_bizdate) w;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "py_winrank_batch FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }

    strncpy(rec.biz_date, bizdate, sizeof(rec.biz_date)-1); rec.biz_date[sizeof(rec.biz_date)-1] = 0;
    rec.peak_running = h_peak;
    printf(">>> py_winrank_batch COMMIT: date=%s peak_running=%ld\n", rec.biz_date, rec.peak_running);

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