/*
 * st_biweekly_batch.pgc - 격주 정산 지급 예정 배치 (XA 배치).
 * 당일 정산을 가맹점별 net 으로 집계하고, 영업일 기준 10일 뒤(약 2주) 지급일을 미리
 * 계산해 지급 원장(st_payment)에 지급 예정(SCHEDULED)으로 등록한다.
 * 사용법: st_biweekly_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "st_dbio.h"
#include "acq_common.h"
#include "st_biweekly_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    st_biweekly_rec_t rec;
    char cur[16], nxt[16], paydate[16];
    int i;
    memset(&rec, 0, sizeof(rec));
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_mid[64];
    long h_net;
    EXEC SQL END DECLARE SECTION;

    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    strncpy(cur, bizdate, sizeof(cur)-1); cur[sizeof(cur)-1] = 0;
    for (i = 0; i < 10; i++) {                        /* 지급일 = 영업일 +10 */
        if (acq_next_bizday(cur, nxt) < 0) { fprintf(stderr, "DATE FAIL\n"); return 1; }
        strncpy(cur, nxt, sizeof(cur)-1); cur[sizeof(cur)-1] = 0;
    }
    strncpy(paydate, cur, sizeof(paydate)-1); paydate[sizeof(paydate)-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 biweekly_bc CURSOR FOR
        SELECT merchant_id, coalesce(sum(net),0) FROM settlement
        WHERE biz_date = :h_bizdate GROUP BY merchant_id ORDER BY merchant_id;
    EXEC SQL OPEN biweekly_bc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }
    for (;;) {
        long pay;
        EXEC SQL FETCH biweekly_bc INTO :h_mid, :h_net;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE biweekly_bc; tpabort(0); return 1; }
        if (h_net <= 0) continue;
        pay = stdb_insert_payment(h_mid, h_net, paydate, "SCHEDULED", bizdate);
        if (pay < 0) { EXEC SQL CLOSE biweekly_bc; tpabort(0); return 1; }
        rec.merchants++; rec.sched_total += h_net; rec.pay_last = pay;
        printf("    SCHED %-8s net=%ld paydate=%s\n", h_mid, h_net, paydate);
    }
    EXEC SQL CLOSE biweekly_bc;

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