/*
 * CL_SUMMARY.pgc - cl 모듈 서비스 CL_SUMMARY (one service = one file).
 * 마감 요약: 스냅샷 gross/fee/net 합계 반환.
 * 이전 인라인 cl_svr.pgc 에서 분리; 호출자의 XA 브랜치에서 수행(EXEC SQL CONNECT 없음).
 * cl_svr 가 tpsvrinit 에서 tpadvertise 로 광고한다.
 */
#include "CL_SUMMARY.h"

void CL_SUMMARY(TPSVCINFO *p)
{
    UBFH *b = (UBFH *)p->data;
    char svc[24];
    char logmsg[192];
    char o_msg[128];
    long o_rc = 0, o_count = 0, o_amount = 0;
    int z_sev = 0, z_comp = 0;
    char z_msg[64];
    char z_buf[192];
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    char h_period[24];
    char h_svc[24];
    char h_logmsg[192];
    long h_cid, h_cnt, h_g, h_f, h_nt;
    long h_zn, h_zcnt, h_zamt;
    long h_zopen, h_zsev;
    long h_kcid;
    char h_zbuf[192];
    EXEC SQL END DECLARE SECTION;
    h_bizdate[0] = 0; h_period[0] = 0; h_zbuf[0] = 0;
    z_msg[0] = 0; z_buf[0] = 0; h_zopen = 0; h_zsev = 0;


    /* --- 섹션9: 진입 로깅 --- */
    strcpy(svc, "CL_SUMMARY");
    userlog("CL_SUMMARY 진입: 마감처리 시작 (요약)", svc);

    h_cid = getl(b, T_ID1);

    /* --- 섹션1: 입력 검증부 --- */
    if (h_cid <= 0) {
        setl(b, T_RC, 6301);
        Bchg(b, T_MSG, 0, "대상 마감ID 필수", 0L); FAIL(b);
    }

    /* --- 섹션2: 마감 존재 확인부 --- */
    EXEC SQL SELECT count(*) INTO :h_cnt FROM cl_close_log
        WHERE close_id = :h_cid;
    if (sqlca.sqlcode < 0) { setl(b, T_RC, 6302); FAIL(b); }
    if (h_cnt == 0) {
        setl(b, T_RC, 6303);
        Bchg(b, T_MSG, 0, "마감이력 미존재", 0L); FAIL(b);
    }

    /* --- 섹션4: 스냅샷 gross/fee/net 합계부 --- */
    EXEC SQL SELECT count(*), coalesce(sum(gross_amount),0),
                    coalesce(sum(fee_amount),0), coalesce(sum(net_amount),0)
        INTO :h_cnt, :h_g, :h_f, :h_nt
        FROM cl_snapshot WHERE close_id = :h_cid;
    if (sqlca.sqlcode < 0) { setl(b, T_RC, 6304); FAIL(b); }

    /* --- 섹션3: 요약 규모 분기부 --- */
    if (h_cnt == 0) {
        o_rc = 1; strcpy(o_msg, "스냅샷 없음");
    } else if (h_g == h_f + h_nt) {
        o_rc = 0; strcpy(o_msg, "gross=fee+net 정합");
    } else {
        o_rc = 2; strcpy(o_msg, "gross<>fee+net 불일치");
    }
    setl(b, T_GROSS, h_g);
    setl(b, T_FEE, h_f);
    setl(b, T_NET, h_nt);
    o_count = h_cnt; o_amount = h_g;

    /* --- 섹션6b: 마감 집계/요약 재산출부 --- */
    EXEC SQL SELECT count(*), coalesce(sum(txn_count),0),
                    coalesce(sum(total_amount),0)
        INTO :h_zn, :h_zcnt, :h_zamt
        FROM cl_close_log
        WHERE status <> 'X'
          AND (:h_period = '' OR period_key = :h_period);
    if (sqlca.sqlcode < 0) {
        userlog("CL_SUMMARY 마감요약 재집계 실패[%d] - 요약 생략", sqlca.sqlcode);
        h_zn = 0; h_zcnt = 0; h_zamt = 0;
    }
    setl(b, T_ARG6, h_zcnt);
    setl(b, T_ARG7, h_zn);

    /* --- 섹션3c: 마감 규모별 추가 업무규칙 분기부 --- */
    if (h_zn == 0) {
        z_sev = 0;
        strcpy(z_msg, "마감이력 없음");
    } else if (h_zamt >= 1000000000L) {
        z_sev = 3;
        strcpy(z_msg, "대규모 마감기간");
    } else if (h_zamt >= 100000000L) {
        z_sev = 2;
        strcpy(z_msg, "중규모 마감기간");
    } else {
        z_sev = 1;
        strcpy(z_msg, "소규모 마감기간");
    }
    h_zsev = (long)z_sev;

    /* --- 섹션7: 예외/보상 판정부 (부분처리 방지) --- */
    if (o_rc != 0) {
        z_comp = 1;
        EXEC SQL SELECT count(*) INTO :h_zopen FROM cl_close_log
            WHERE status = 'O'
              AND (:h_bizdate = '' OR period_key = :h_bizdate);
        if (sqlca.sqlcode < 0) h_zopen = 0;
        if (h_zopen > 0)
            userlog("CL_SUMMARY 경고: 미완결 개시(O) %ld건 잔존 - 보상대상", h_zopen);
        userlog("CL_SUMMARY 예외분기 rc=%ld sev=%d - 상태전이 실패 이력 적재",
                o_rc, z_sev);
    } else {
        z_comp = 0;
        h_zopen = 0;
    }

    /* --- 섹션5b: 처리 요약 이력 적재부 --- */
    snprintf(z_buf, sizeof(z_buf), "%s sev=%d comp=%d open=%ld %s",
             svc, z_sev, z_comp, h_zopen, z_msg);
    strncpy(h_zbuf, z_buf, sizeof(h_zbuf)-1);
    h_zbuf[sizeof(h_zbuf)-1] = 0;
    strncpy(h_svc, svc, sizeof(h_svc)-1); h_svc[sizeof(h_svc)-1] = 0;
    EXEC SQL INSERT INTO cm_log (log_id, svc_name, log_level, msg, biz_date)
        VALUES (nextval('cm_log_seq'), :h_svc,
                CASE WHEN :h_zsev > 2 THEN 'W' ELSE 'I' END, :h_zbuf,
                COALESCE(NULLIF(:h_bizdate,'')::date, CURRENT_DATE));
    if (sqlca.sqlcode < 0)
        userlog("CL_SUMMARY 요약이력 적재 실패[%d] - 업무는 계속", sqlca.sqlcode);
    setl(b, T_ARG8, h_zsev);

    /* --- 섹션5: 이력/감사 적재 (cm_log, best-effort) --- */
    snprintf(logmsg, sizeof(logmsg), "CL_SUMMARY 요약 cnt=%ld amt=%ld rc=%ld",
             o_count, o_amount, o_rc);
    strncpy(h_logmsg, logmsg, sizeof(h_logmsg)-1);
    h_logmsg[sizeof(h_logmsg)-1] = 0;
    strncpy(h_svc, svc, sizeof(h_svc)-1); h_svc[sizeof(h_svc)-1] = 0;
    EXEC SQL INSERT INTO cm_log (log_id, svc_name, log_level, msg, biz_date)
        VALUES (nextval('cm_log_seq'), :h_svc, 'I', :h_logmsg,
                COALESCE(NULLIF(:h_bizdate,'')::date, CURRENT_DATE));
    if (sqlca.sqlcode < 0)
        userlog("CL_SUMMARY 감사로그 적재 실패[%d] - 업무는 계속", sqlca.sqlcode);

    /* --- 섹션8: 응답부 --- */
    setl(b, T_RC, o_rc);
    setl(b, T_COUNT, o_count);
    setl(b, T_GROSS, o_amount);
    Bchg(b, T_MSG, 0, o_msg, 0L);
    userlog("CL_SUMMARY 완료: rc=%ld count=%ld amount=%ld", o_rc, o_count, o_amount);
    OK(b);
}

/* vim: set ts=4 sw=4 et smartindent: */
