/*
 * cl_chnclose_batch.pgc - cl 채널별 일괄 마감 배치 (그룹 커서 + XA).
 *
 * 영업일의 매입을 채널(POS/EDC/EDI/FOREIGN) 그룹 커서로 순회하며 채널마다
 * CHN 마감이력을 한 건씩 생성한다. 전 구간 ONE global XA (tpcommit = 2PC).
 * host 변수는 전용 카피북 cl_chnclose_cpy.h 를 EXEC SQL INCLUDE 로 가져온다.
 * Usage: cl_chnclose_batch [YYYY-MM-DD]
 */
#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 made = 0;

    EXEC SQL INCLUDE cl_chnclose_cpy;

    strncpy(cc_bizdate, bizdate, sizeof(cc_bizdate)-1); cc_bizdate[sizeof(cc_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 bchn CURSOR FOR
        SELECT channel, count(*), coalesce(sum(amount),0) FROM purchase
        WHERE biz_date = :cc_bizdate GROUP BY channel ORDER BY channel;
    EXEC SQL OPEN bchn;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH bchn INTO :cc_chn, :cc_cnt, :cc_amt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE bchn; tpabort(0); return 1; }
        EXEC SQL SELECT nextval('cl_close_seq') INTO :cc_cid;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE bchn; tpabort(0); return 1; }
        snprintf(cc_memo, sizeof(cc_memo), "채널마감:%s", cc_chn);
        EXEC SQL INSERT INTO cl_close_log
            (close_id, close_type, period_key, biz_date, status, txn_count, total_amount, memo)
            VALUES (:cc_cid, 'CHN', :cc_bizdate, :cc_bizdate, 'C', :cc_cnt, :cc_amt, :cc_memo);
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE bchn; tpabort(0); return 1; }
        printf("    채널 %-8s cid=%ld cnt=%ld amt=%ld\n", cc_chn, cc_cid, cc_cnt, cc_amt);
        made++;
    }
    EXEC SQL CLOSE bchn;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> cl_chnclose_batch COMMIT: bizdate=%s 채널마감 %ld건 생성\n", bizdate, made);

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