/*
 * cl_semimonth_batch.pgc - cl 반월 마감 배치 (전반/후반 집계 + SEMIMON 마감 + XA).
 *
 * 기준일이 속한 반월(전반 1~15 / 후반 16~말) 구간 매입을 집계해 SEMIMON 마감이력을 기록.
 * host 변수는 전용 카피북 cl_semimonth_cpy.h 를 EXEC SQL INCLUDE 로 가져온다.
 * Usage: cl_semimonth_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 cid, half;
    char period[24], memo[32];

    EXEC SQL INCLUDE cl_semimonth_cpy;

    strncpy(sm_bizdate, bizdate, sizeof(sm_bizdate)-1); sm_bizdate[sizeof(sm_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 extract(day from :sm_bizdate::date)::int,
                    to_char(:sm_bizdate::date, 'YYYY-MM') INTO :sm_day, :sm_ym;
    if (sqlca.sqlcode < 0) { tpabort(0); return 1; }
    half = (sm_day <= 15) ? 1 : 2;
    sm_lo = (half == 1) ? 1 : 16;
    sm_hi = (half == 1) ? 15 : 31;

    EXEC SQL SELECT count(*), coalesce(sum(amount),0) INTO :sm_cnt, :sm_amt
        FROM purchase WHERE to_char(biz_date,'YYYY-MM') = :sm_ym
          AND extract(day from biz_date) BETWEEN :sm_lo AND :sm_hi;
    if (sqlca.sqlcode < 0) { tpabort(0); return 1; }

    snprintf(period, sizeof(period), "%s-H%ld", sm_ym, half);
    snprintf(memo, sizeof(memo), "반월마감(배치):%s", (half == 1) ? "전반" : "후반");
    cid = cldb_next_close_id();
    if (cid < 0) { tpabort(0); return 1; }
    if (cldb_insert_close(cid, "SEMIMON", period, bizdate, "C", sm_cnt, sm_amt, memo) < 0) {
        tpabort(0); return 1;
    }

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> cl_semimonth_batch COMMIT: %s %s cid=%ld 건수=%ld\n",
           sm_ym, (half==1)?"전반":"후반", cid, sm_cnt);

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