/*
 * py_advrepay_batch.pgc - py 선지급 분할 상환 배치 (커서 + adjust 기록, XA).
 *
 * 잔여 net 이 남은 ADVANCE 지급건을 커서로 훑어 상환률(bps)만큼 회수:
 * py_adjust 음수 기록 + net 차감, 완납 시 마감(X) 전이까지 처리한다.
 * host 변수는 전용 카피북 py_advrepay_cpy.h 를 EXEC SQL INCLUDE.
 * Usage: py_advrepay_batch [YYYY-MM-DD] [RATE_BPS]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    long repaid = 0, repaid_amt = 0, closed = 0;

    EXEC SQL INCLUDE py_advrepay_cpy;

    strncpy(c_bizdate, bizdate, sizeof(c_bizdate)-1); c_bizdate[sizeof(c_bizdate)-1] = 0;
    c_bps = (argc > 2) ? atol(argv[2]) : 1000;   /* 기본 회당 10% 상환 */
    if (c_bps <= 0 || c_bps > 10000) c_bps = 1000;

    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(120, 0) < 0) { fprintf(stderr, "tpbegin FAIL: %s\n", tpstrerror(tperrno)); return 1; }

    EXEC SQL DECLARE par CURSOR FOR
        SELECT payout_id, net FROM py_payout
         WHERE channel = 'ADVANCE' AND net > 0 AND status NOT IN ('C','V','X')
         ORDER BY payout_id;
    EXEC SQL OPEN par;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH par INTO :c_pid, :c_net;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE par; tpabort(0); return 1; }
        c_repay = c_net * c_bps / 10000;
        if (c_repay <= 0) c_repay = c_net;      /* 소액 잔여는 완납 처리 */
        c_newnet = c_net - c_repay;
        c_adj = -c_repay;
        EXEC SQL INSERT INTO py_adjust (adj_id, payout_id, delta, reason, biz_date)
            VALUES (nextval('py_adjust_seq'), :c_pid, :c_adj, '선지급상환(배치)', :c_bizdate);
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE par; tpabort(0); return 1; }
        EXEC SQL UPDATE py_payout
            SET net = :c_newnet,
                status = CASE WHEN :c_newnet <= 0 THEN 'X' ELSE status END,
                updated_at = now()
            WHERE payout_id = :c_pid;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE par; tpabort(0); return 1; }
        repaid++; repaid_amt += c_repay;
        if (c_newnet <= 0) closed++;
    }
    EXEC SQL CLOSE par;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> py_advrepay_batch COMMIT: bps=%ld 상환=%ld건/%ld원 완납마감=%ld건\n",
           c_bps, repaid, repaid_amt, closed);

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