/*
 * cl_daily_batch.pgc - cl 일 마감 배치 (미마감 점검 + 커서 M->S + XA).
 *
 * ATMI client: tpinit/tpopen open the ECPG XA RM, tpbegin starts ONE global
 * transaction. 먼저 당일 대사완료(M) 미마감 매입 건수를 점검하고, 커서로 각 건을
 * 정산완료(S)로 마감 전환한 뒤, 당일 마감이력(close_log, DAILY)을 집계와 함께
 * 기록한다. tpcommit 이 XA 2PC 를 구동. Usage: cl_daily_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "cl_dbio.h"

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

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_pid, h_unclosed, h_cnt, h_amt;
    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; }

    /* 1) 미마감(대사완료 M) 점검 */
    EXEC SQL SELECT count(*) INTO :h_unclosed FROM purchase
        WHERE biz_date = :h_bizdate AND status = 'M';
    if (sqlca.sqlcode < 0) { fprintf(stderr, "COUNT FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    printf(">>> cl_daily_batch 미마감(M) 점검: bizdate=%s 대상=%ld건\n", bizdate, h_unclosed);

    /* 2) 커서로 M -> S 마감 전환 */
    EXEC SQL DECLARE cdc CURSOR FOR
        SELECT purchase_id FROM purchase
        WHERE biz_date = :h_bizdate AND status = 'M'
        ORDER BY purchase_id;
    EXEC SQL OPEN cdc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH cdc INTO :h_pid;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE cdc; tpabort(0); return 1; }
        EXEC SQL UPDATE purchase SET status = 'S', updated_at = now() WHERE purchase_id = :h_pid;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE cdc; tpabort(0); return 1; }
        closed++;
    }
    EXEC SQL CLOSE cdc;

    /* 3) 당일 집계 + 마감이력(DAILY) 기록 (via dbio) */
    EXEC SQL SELECT count(*), coalesce(sum(amount),0) INTO :h_cnt, :h_amt
        FROM purchase WHERE biz_date = :h_bizdate;
    if (sqlca.sqlcode < 0) { tpabort(0); return 1; }
    cid = cldb_next_close_id();
    if (cid < 0) { tpabort(0); return 1; }
    if (cldb_insert_close(cid, "DAILY", bizdate, bizdate, "C", h_cnt, h_amt, "일마감(배치)") < 0) {
        tpabort(0); return 1;
    }

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> cl_daily_batch COMMIT: bizdate=%s 마감전환=%ld cid=%ld 총건수=%ld\n",
           bizdate, closed, cid, h_cnt);

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