/*
 * cl_mainclose_batch.pgc - cl 본마감 승격 배치 (가마감 재집계 + O->C 승격 + XA).
 *
 * 당일 가마감(TENT, status=O) 이력을 당일 전체 매입으로 재집계해 확정(status=C)으로 승격.
 * host 변수는 전용 카피북 cl_mainclose_cpy.h 를 EXEC SQL INCLUDE 로 가져온다.
 * Usage: cl_mainclose_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 promoted;

    EXEC SQL INCLUDE cl_mainclose_cpy;

    strncpy(mc_bizdate, bizdate, sizeof(mc_bizdate)-1); mc_bizdate[sizeof(mc_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 SELECT count(*), coalesce(sum(amount),0) INTO :mc_cnt, :mc_amt
        FROM purchase WHERE biz_date = :mc_bizdate;
    if (sqlca.sqlcode < 0) { tpabort(0); return 1; }

    EXEC SQL UPDATE cl_close_log
        SET status = 'C', txn_count = :mc_cnt, total_amount = :mc_amt, memo = '본마감(배치)', updated_at = now()
        WHERE close_type = 'TENT' AND period_key = :mc_bizdate AND status = 'O';
    if (sqlca.sqlcode < 0) { tpabort(0); return 1; }
    promoted = (long)sqlca.sqlerrd[2];

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> cl_mainclose_batch COMMIT: %s 본마감 승격 %ld건 확정건수=%ld\n", bizdate, promoted, mc_cnt);

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