/* 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/mg_ol_0024.pgc"
/* @tier medium @module mg @transform msg-gateway-online */
/*
 * mg_ol_0024.pgc - 전문게이트웨이 전문 타임아웃 판정 서비스 (MG_OL_0024)  [tier=medium]
 *
 * 전문 송신시각(SENDTIME)과 현재시각(NOWTIME)의 차이를 밀리초로 환산하여
 * 임계값(기본 5000ms) 초과 여부로 타임아웃을 판정한다. 자정 경과(day-wrap)
 * 를 보정하며, 판정결과(TIMEOUT)와 경과시간(ELAPSEDMS)을 응답한다.
 * (순수 계산 로직 - DB 접근 없음)
 */
#include <stdio.h>
#include <string.h>

#include "txcore.h"
#include "acq_util.h"
#include "mg_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 17 "app/online/mg_ol_0024.pgc"


#define MG_TIMEOUT_DEFAULT_MS  5000L
#define MG_MS_PER_DAY          86400000L

/* HHMMSS 6자리를 자정기준 밀리초로 환산 (형식오류 시 -1) */
static long hhmmss_to_ms(const char *s)
{
    int i, h, m, sec;

    if (s == NULL || strlen(s) < 6)
        return -1;
    for (i = 0; i < 6; i++) {
        if (s[i] < '0' || s[i] > '9')
            return -1;
    }
    h   = (s[0] - '0') * 10 + (s[1] - '0');
    m   = (s[2] - '0') * 10 + (s[3] - '0');
    sec = (s[4] - '0') * 10 + (s[5] - '0');
    if (h > 23 || m > 59 || sec > 59)
        return -1;
    return ((long)h * 3600L + (long)m * 60L + (long)sec) * 1000L;
}

TX_SERVICE(MG_OL_0024, ctx)
{
    char sendtime[16], nowtime[16];
    long threshold = MG_TIMEOUT_DEFAULT_MS;
    long send_ms, now_ms, elapsed;
    int  is_timeout;

    tx_log(TX_LOG_INFO, "[MG_OL_0024] 전문 타임아웃 판정 서비스 진입");

    /* 1) 송신시각/현재시각 수신 (HHMMSS) */
    if (tx_buf_get(ctx->in, "SENDTIME", sendtime, sizeof(sendtime)) != TX_OK ||
        tx_buf_get(ctx->in, "NOWTIME", nowtime, sizeof(nowtime)) != TX_OK) {
        tx_log(TX_LOG_ERROR, "[MG_OL_0024] 시각 필드(SENDTIME/NOWTIME) 누락");
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

    /* 임계값은 선택 입력 (미제출 시 기본값) */
    tx_buf_getlong(ctx->in, "THRESHMS", &threshold);
    if (threshold <= 0)
        threshold = MG_TIMEOUT_DEFAULT_MS;

    /* 2) 시각 파싱 */
    send_ms = hhmmss_to_ms(sendtime);
    now_ms  = hhmmss_to_ms(nowtime);
    if (send_ms < 0 || now_ms < 0) {
        tx_log(TX_LOG_WARN, "[MG_OL_0024] 시각 형식 오류 send=%s now=%s",
               sendtime, nowtime);
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESP", RESP_INVALID);
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

    /* 3) 경과시간 계산 (자정 경과 보정) */
    elapsed = now_ms - send_ms;
    if (elapsed < 0)
        elapsed += MG_MS_PER_DAY;

    is_timeout = (elapsed > threshold);

    /* 4) 판정결과 응답 */
    tx_buf_reset(ctx->out);
    tx_buf_sets(ctx->out, "RESP", RESP_OK);
    tx_buf_setlong(ctx->out, "ELAPSEDMS", elapsed);
    tx_buf_setlong(ctx->out, "THRESHMS", threshold);
    tx_buf_sets(ctx->out, "TIMEOUT", is_timeout ? "Y" : "N");

    if (is_timeout)
        tx_log(TX_LOG_WARN, "[MG_OL_0024] 타임아웃 판정 경과=%ldms 임계=%ldms",
               elapsed, threshold);
    else
        tx_log(TX_LOG_INFO, "[MG_OL_0024] 정상 경과=%ldms 임계=%ldms",
               elapsed, threshold);

    tx_return(ctx, TX_OK, ctx->out);
}
