/*
 * cl_halfclose_batch.pgc - cl 반기 결산 마감 배치 (월별 소계 + 반기 마감 + XA).
 *
 * 연도/반기(1|2)를 받아 반기 구간의 월별 소계를 커서로 출력한 뒤 반기 전체를
 * BETWEEN 집계해 HALF 마감이력(YYYY-Hn, status C)을 생성한다.
 * 동일 반기 기존 마감이 있으면 거절. 전 구간 ONE global XA.
 * host 변수는 전용 카피북 cl_halfclose_cpy.h 를 EXEC SQL INCLUDE 로 가져온다.
 * Usage: cl_halfclose_batch [YYYY] [1|2]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>

int main(int argc, char **argv)
{
    const char *year = (argc > 1) ? argv[1] : "2026";
    int half = (argc > 2) ? atoi(argv[2]) : 1;
    long months = 0;

    EXEC SQL INCLUDE cl_halfclose_cpy;

    if (half != 1 && half != 2) { fprintf(stderr, "반기는 1|2 만 허용\n"); return 1; }
    if (half == 1) {
        snprintf(hf_from, sizeof(hf_from), "%s-01-01", year);
        snprintf(hf_to,   sizeof(hf_to),   "%s-06-30", year);
    } else {
        snprintf(hf_from, sizeof(hf_from), "%s-07-01", year);
        snprintf(hf_to,   sizeof(hf_to),   "%s-12-31", year);
    }
    snprintf(hf_period, sizeof(hf_period), "%s-H%d", year, half);

    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 SELECT count(*) INTO :hf_cnt FROM cl_close_log
        WHERE close_type = 'HALF' AND period_key = :hf_period AND status <> 'X';
    if (sqlca.sqlcode < 0) { tpabort(0); return 1; }
    if (hf_cnt > 0) {
        fprintf(stderr, "cl_halfclose_batch: %s 반기마감 기존재 - 중복 불가\n", hf_period);
        tpabort(0); tpclose(); tpterm();
        return 2;
    }

    EXEC SQL DECLARE bhalf CURSOR FOR
        SELECT to_char(biz_date,'YYYY-MM'), count(*), coalesce(sum(amount),0)
        FROM purchase WHERE biz_date BETWEEN :hf_from AND :hf_to
        GROUP BY 1 ORDER BY 1;
    EXEC SQL OPEN bhalf;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH bhalf INTO :hf_mon, :hf_mcnt, :hf_mamt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE bhalf; tpabort(0); return 1; }
        printf("    월소계 %s cnt=%ld amt=%ld\n", hf_mon, hf_mcnt, hf_mamt);
        months++;
    }
    EXEC SQL CLOSE bhalf;

    EXEC SQL SELECT count(*), coalesce(sum(amount),0) INTO :hf_cnt, :hf_amt
        FROM purchase WHERE biz_date BETWEEN :hf_from AND :hf_to;
    if (sqlca.sqlcode < 0) { tpabort(0); return 1; }
    EXEC SQL SELECT nextval('cl_close_seq') INTO :hf_cid;
    if (sqlca.sqlcode < 0) { tpabort(0); return 1; }
    EXEC SQL INSERT INTO cl_close_log
        (close_id, close_type, period_key, biz_date, status, txn_count, total_amount, memo)
        VALUES (:hf_cid, 'HALF', :hf_period, :hf_to, 'C', :hf_cnt, :hf_amt, '반기결산');
    if (sqlca.sqlcode < 0) { tpabort(0); return 1; }

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> cl_halfclose_batch COMMIT: %s cid=%ld 월=%ld개 cnt=%ld amt=%ld\n",
           hf_period, hf_cid, months, hf_cnt, hf_amt);

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