/* Processed by ecpg (15.18 (Debian 15.18-0+deb12u1)) */
/* These include files are added by the preprocessor */
#include <ecpglib.h>
#include <ecpgerrno.h>
#include <sqlca.h>
/* End of automatic include section */

#line 1 "app/online/cl_ol_0025.pgc"
/* @tier medium @module cl @transform closing-online */
/*
 * cl_ol_0025.pgc - 마감 온라인 서비스 (CL_OL_0025)  [tier=medium]
 *
 * 알림 재발송
 * ----------------------------------------------------------------------
 * 요청 영업일(BIZDATE)의 미마감(R) 건수와 불일치(U) 건수를 각각 개별
 * 조회한 뒤, 두 값을 바탕으로 마감 지연/불일치 알림 메시지를 구성하여
 * ALERT 유형 응답으로 반환한다. 미마감·불일치가 모두 0 이면
 * 정상(알림불필요)으로 표시한다.
 *
 * 미마감/불일치 규모에 따라 심각도(SEVERITY: NONE/WARN/CRIT)를 부여
 * 하고, 정산완료(S) 건수를 함께 조회하여 진행 맥락을 알림에 포함한다.
 * 재발송 대상 수신처(TARGET)와 감사추적 REQID 는 선택 입력으로 받는다.
 */
#include <stdio.h>
#include <string.h>

#include "txcore.h"
#include "txcore_dbio.h"
#include "acq_util.h"
#include "cl_core.h"


#line 1 "/usr/include/postgresql/sqlca.h"
#ifndef POSTGRES_SQLCA_H
#define POSTGRES_SQLCA_H

#ifndef PGDLLIMPORT
#if  defined(WIN32) || defined(__CYGWIN__)
#define PGDLLIMPORT __declspec (dllimport)
#else
#define PGDLLIMPORT
#endif							/* __CYGWIN__ */
#endif							/* PGDLLIMPORT */

#define SQLERRMC_LEN	150

#ifdef __cplusplus
extern "C"
{
#endif

struct sqlca_t
{
	char		sqlcaid[8];
	long		sqlabc;
	long		sqlcode;
	struct
	{
		int			sqlerrml;
		char		sqlerrmc[SQLERRMC_LEN];
	}			sqlerrm;
	char		sqlerrp[8];
	long		sqlerrd[6];
	/* Element 0: empty						*/
	/* 1: OID of processed tuple if applicable			*/
	/* 2: number of rows processed				*/
	/* after an INSERT, UPDATE or				*/
	/* DELETE statement					*/
	/* 3: empty						*/
	/* 4: empty						*/
	/* 5: empty						*/
	char		sqlwarn[8];
	/* Element 0: set to 'W' if at least one other is 'W'	*/
	/* 1: if 'W' at least one character string		*/
	/* value was truncated when it was			*/
	/* stored into a host variable.             */

	/*
	 * 2: if 'W' a (hopefully) non-fatal notice occurred
	 */	/* 3: empty */
	/* 4: empty						*/
	/* 5: empty						*/
	/* 6: empty						*/
	/* 7: empty						*/

	char		sqlstate[5];
};

struct sqlca_t *ECPGget_sqlca(void);

#ifndef POSTGRES_ECPG_INTERNAL
#define sqlca (*ECPGget_sqlca())
#endif

#ifdef __cplusplus
}
#endif

#endif

#line 24 "app/online/cl_ol_0025.pgc"


#define CL_OL_0025_CRIT_THRESHOLD 10

TX_SERVICE(CL_OL_0025, ctx)
{
    char bizdate[16];
    char reqid[32];
    char target[32];
    char alert[TX_VAL_LEN];
    const char *severity;
    long recv_cnt, fail_cnt, settled_cnt, done_cnt;
    long pending, total_cnt;
    int  need_alert;

    tx_log(TX_LOG_INFO, "[CL_OL_0025] 알림 재발송 서비스 진입");

    /* 1) 입력 수신 및 검증 */
    if (tx_buf_get(ctx->in, "BIZDATE", bizdate, sizeof(bizdate)) != TX_OK) {
        tx_log(TX_LOG_ERROR, "[CL_OL_0025] BIZDATE 누락");
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_INVALID);
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }
    if (tx_buf_get(ctx->in, "REQID", reqid, sizeof(reqid)) != TX_OK)
        strncpy(reqid, "-", sizeof(reqid) - 1);
    if (tx_buf_get(ctx->in, "TARGET", target, sizeof(target)) != TX_OK)
        strncpy(target, "OPS-DESK", sizeof(target) - 1);

    if (!date_is_valid(bizdate)) {
        tx_log(TX_LOG_WARN, "[CL_OL_0025] 영업일 형식 오류 date=%s", bizdate);
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_INVALID);
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

    /* 2) 미마감(R)/불일치(U)/정산완료(S) 건수 개별 조회 */
    recv_cnt    = cl_rec_count(bizdate, CL_ST_RECV);
    fail_cnt    = cl_rec_count(bizdate, CL_ST_FAIL);
    settled_cnt = cl_rec_count(bizdate, CL_ST_SETTLED);
    done_cnt    = cl_rec_count(bizdate, CL_ST_DONE);
    if (recv_cnt < 0 || fail_cnt < 0 || settled_cnt < 0 || done_cnt < 0) {
        tx_log(TX_LOG_ERROR, "[CL_OL_0025] 건수 조회 실패 date=%s", bizdate);
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_SYSERR);
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }
    total_cnt = recv_cnt + done_cnt + fail_cnt + settled_cnt;

    /*
     * 3) 심각도 판정 및 알림 메시지 구성
     *    - pending(미마감+불일치)이 0 이면 알림 불필요(NONE)
     *    - 임계(CRIT_THRESHOLD) 이상이면 즉시 조치 대상(CRIT)
     *    - 그 외 잔량이 있으면 주의(WARN)
     */
    pending    = recv_cnt + fail_cnt;
    need_alert = (pending > 0) ? 1 : 0;
    if (pending == 0)
        severity = "NONE";
    else if (pending >= CL_OL_0025_CRIT_THRESHOLD)
        severity = "CRIT";
    else
        severity = "WARN";

    if (need_alert)
        snprintf(alert, sizeof(alert),
                 "[마감알림/%s] %s 미마감 %ld건, 불일치 %ld건 (정산완료 %ld건) - 확인 요망",
                 severity, bizdate, recv_cnt, fail_cnt, settled_cnt);
    else
        snprintf(alert, sizeof(alert),
                 "[마감알림/%s] %s 마감 정상완료(정산완료 %ld건) - 조치 불필요",
                 severity, bizdate, settled_cnt);

    tx_buf_reset(ctx->out);
    tx_buf_sets(ctx->out, "RESPCODE", RESP_OK);
    tx_buf_sets(ctx->out, "TYPE", "ALERT");
    tx_buf_sets(ctx->out, "BIZDATE", bizdate);
    tx_buf_sets(ctx->out, "REQID", reqid);
    tx_buf_sets(ctx->out, "TARGET", target);
    tx_buf_setlong(ctx->out, "RECVCNT", recv_cnt);
    tx_buf_setlong(ctx->out, "FAILCNT", fail_cnt);
    tx_buf_setlong(ctx->out, "DONECNT", done_cnt);
    tx_buf_setlong(ctx->out, "SETTLEDCNT", settled_cnt);
    tx_buf_setlong(ctx->out, "TOTALCNT", total_cnt);
    tx_buf_setlong(ctx->out, "PENDING", pending);
    tx_buf_sets(ctx->out, "SEVERITY", severity);
    tx_buf_sets(ctx->out, "NEEDALERT", need_alert ? "Y" : "N");
    tx_buf_sets(ctx->out, "ALERTMSG", alert);
    /* 미마감 우세/불일치 우세 구분 (조치 우선순위 힌트) */
    tx_buf_sets(ctx->out, "FOCUS",
                (fail_cnt > recv_cnt) ? "UNMATCH" : "PENDING");

    tx_log(TX_LOG_INFO,
           "[CL_OL_0025] 완료 date=%s R=%ld U=%ld sev=%s 발송=%s target=%s",
           bizdate, recv_cnt, fail_cnt, severity,
           need_alert ? "Y" : "N", target);
    tx_return(ctx, TX_OK, ctx->out);
}
