/*
 * lg_dcweight_batch.pgc - lg 계정 진행잔액 최고점 (윈도우 배치, XA).
 *
 * Computes the peak running balance (debit +, credit -) of an account ordered
 * by line_id using a SUM() OVER window, inside ONE XA transaction.
 * Usage: lg_dcweight_batch [ACCT] [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "lg_dcweight_batch.h"

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

    EXEC SQL BEGIN DECLARE SECTION;
    char h_acct[32], h_bizdate[16];
    long h_peak;
    EXEC SQL END DECLARE SECTION;

    strncpy(h_acct, acct, sizeof(h_acct)-1); h_acct[sizeof(h_acct)-1] = 0;
    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_bal),0) INTO :h_peak FROM (
        SELECT sum(CASE WHEN dc = 'D' THEN amount ELSE -amount END)
               OVER (ORDER BY line_id) AS run_bal
        FROM lg_ledger_line WHERE acct = :h_acct AND biz_date = :h_bizdate) w;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "lg_dcweight_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.acct, acct, sizeof(rec.acct)-1); rec.acct[sizeof(rec.acct)-1] = 0;
    strncpy(rec.biz_date, bizdate, sizeof(rec.biz_date)-1); rec.biz_date[sizeof(rec.biz_date)-1] = 0;
    rec.peak = h_peak;
    printf(">>> lg_dcweight_batch COMMIT: acct=%s date=%s peak=%ld\n", rec.acct, rec.biz_date, rec.peak);

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