/*
 * ac_settledue_batch.pgc - ac 정산예정 대기열 집계 배치 (NOT EXISTS, XA).
 *
 * ATMI client: 대사완료(M) 상태이나 정산행이 아직 없는 매입을 가맹점별로
 * 묶어 정산예정액을 산출한다. 가맹점별 라인 출력 후 전체 합계로 마감.
 * Usage: ac_settledue_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "ac_settledue_batch.h"

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

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_merch[64];
    long h_n, h_net;
    EXEC SQL END DECLARE SECTION;

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

    EXEC SQL DECLARE sdb_cur CURSOR FOR
        SELECT u.merchant_id, count(*), sum(u.net)
        FROM purchase u
        WHERE u.biz_date = :h_bizdate AND u.status = 'M'
          AND NOT EXISTS (SELECT 1 FROM settlement s WHERE s.purchase_id = u.purchase_id)
        GROUP BY u.merchant_id ORDER BY u.merchant_id;
    EXEC SQL OPEN sdb_cur;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "open FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH sdb_cur INTO :h_merch, :h_n, :h_net;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE sdb_cur; fprintf(stderr, "fetch FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }
        printf("  merchant=%s due_n=%ld due_net=%ld\n", h_merch, h_n, h_net);
        cx.merchants++;
        cx.due_count += h_n;
        cx.due_net += h_net;
    }
    EXEC SQL CLOSE sdb_cur;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> ac_settledue_batch COMMIT: bizdate=%s merchants=%ld due_n=%ld due_net=%ld\n",
           bizdate, cx.merchants, cx.due_count, cx.due_net);

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