/*
 * st_recvsweep_batch.pgc - 미수금 상계 스윕 배치 (미수 가맹점 커서 + 상계 + XA).
 * 매입 조인으로 미수금(음수 조정 누계)이 있는 가맹점을 커서로 찾고, 각
 * 가맹점의 당일 예정 지급에서 미수금과 가용액의 min 만큼 상계 차감한다.
 * 사용법: st_recvsweep_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "st_dbio.h"
#include "st_recvsweep_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    st_recvsweep_rec_t rec;
    memset(&rec, 0, sizeof(rec));
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_merch[64];
    long h_recv, h_avail, h_off;
    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 DECLARE recvsweep_bc CURSOR FOR
        SELECT p.merchant_id, -sum(a.delta)
        FROM st_adjust a JOIN purchase p ON p.purchase_id = a.purchase_id
        WHERE a.delta < 0
        GROUP BY p.merchant_id
        HAVING sum(a.delta) < 0
        ORDER BY p.merchant_id;
    EXEC SQL OPEN recvsweep_bc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH recvsweep_bc INTO :h_merch, :h_recv;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE recvsweep_bc; tpabort(0); return 1; }
        EXEC SQL SELECT coalesce(sum(net_amount),0) INTO :h_avail FROM st_payment
            WHERE merchant_id = :h_merch AND biz_date = :h_bizdate AND status = 'SCHEDULED';
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE recvsweep_bc; tpabort(0); return 1; }
        h_off = (h_recv < h_avail) ? h_recv : h_avail;
        if (h_off <= 0) continue;
        EXEC SQL UPDATE st_payment SET net_amount = net_amount - :h_off
            WHERE pay_id = (SELECT min(pay_id) FROM st_payment
                            WHERE merchant_id = :h_merch AND biz_date = :h_bizdate AND status = 'SCHEDULED');
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE recvsweep_bc; tpabort(0); return 1; }
        rec.merchants++;
        rec.offset_sum += h_off;
    }
    EXEC SQL CLOSE recvsweep_bc;

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

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