/* 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_0016.pgc"
/* @tier medium @module cl @transform closing-online */
/*
 * cl_ol_0016.pgc - 마감 온라인 서비스 (CL_OL_0016)  [tier=medium]
 *
 * 마감 확정. 요청 처리키(KEY) 단건에 대해 현재 상태를 확인한 뒤 처리완료(M)
 * 건을 정산완료(S)로 확정한다. 이미 정산완료(S)면 경고로 응답하고, 확정
 * 대상이 아닌 상태(R/U)이면 확정 불가로 응답한다. (singleton SELECT 후
 * 단건 UPDATE; tx_begin/tx_commit)
 */
#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 18 "app/online/cl_ol_0016.pgc"


TX_SERVICE(CL_OL_0016, ctx)
{
    /* exec sql begin declare section */
     
     
     
    
#line 23 "app/online/cl_ol_0016.pgc"
 char h_key [ 16 ] ;
 
#line 24 "app/online/cl_ol_0016.pgc"
 char h_status [ 2 ] ;
 
#line 25 "app/online/cl_ol_0016.pgc"
 long h_amount ;
/* exec sql end declare section */
#line 26 "app/online/cl_ol_0016.pgc"


    char key[16];
    char won[40];

    tx_log(TX_LOG_INFO, "[CL_OL_0016] 마감 확정 서비스 진입");

    /* 1. 요청 검증 : 처리키 필수 */
    if (tx_buf_get(ctx->in, "KEY", key, sizeof(key)) != TX_OK) {
        tx_log(TX_LOG_ERROR, "[CL_OL_0016] KEY 누락");
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_INVALID);
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

    strncpy(h_key, key, sizeof(h_key) - 1);
    h_key[sizeof(h_key) - 1] = '\0';

    /* 2. 현재 상태/금액 단건 조회 (PK singleton SELECT) */
    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "select status , amount from cl_ledger where key = $1 ", 
	ECPGt_char,(h_key),(long)16,(long)1,(16)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, 
	ECPGt_char,(h_status),(long)2,(long)1,(2)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_long,&(h_amount),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EORT);}
#line 49 "app/online/cl_ol_0016.pgc"

    if (sqlca.sqlcode == TX_SQL_NOTFOUND) {
        tx_log(TX_LOG_WARN, "[CL_OL_0016] 원장 없음 key=%s", key);
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_INVALID);
        tx_buf_sets(ctx->out, "KEY", key);
        tx_buf_sets(ctx->out, "MESSAGE", "해당 처리키 원장 없음");
        tx_return(ctx, TX_ENOENT, ctx->out);
        return;
    }
    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("CL_OL_0016 status select");
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_SYSERR);
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }
    h_status[1] = '\0';
    amount_format_won(h_amount, won, sizeof(won));

    /* 3. 이미 확정(S)인 경우 경고 응답 (멱등 처리) */
    if (strcmp(h_status, CL_ST_SETTLED) == 0) {
        tx_log(TX_LOG_WARN, "[CL_OL_0016] 이미 확정 key=%s", key);
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_OK);
        tx_buf_sets(ctx->out, "KEY", key);
        tx_buf_sets(ctx->out, "STATUS", h_status);
        tx_buf_setlong(ctx->out, "AMOUNT", h_amount);
        tx_buf_sets(ctx->out, "CONFIRMED", "Y");
        tx_buf_sets(ctx->out, "MESSAGE", "이미 마감확정된 건");
        tx_return(ctx, TX_OK, ctx->out);
        return;
    }

    /* 4. 확정 대상은 처리완료(M) 만 허용 */
    if (strcmp(h_status, CL_ST_DONE) != 0) {
        tx_log(TX_LOG_WARN, "[CL_OL_0016] 확정 불가 상태 key=%s status=%s",
               key, h_status);
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_INVALID);
        tx_buf_sets(ctx->out, "KEY", key);
        tx_buf_sets(ctx->out, "STATUS", h_status);
        tx_buf_sets(ctx->out, "CONFIRMED", "N");
        tx_buf_sets(ctx->out, "MESSAGE", "처리완료(M) 건만 확정 가능");
        tx_return(ctx, TX_FAIL, ctx->out);
        return;
    }

    /* 5. 확정 트랜잭션 : M → S 단건 UPDATE */
    if (tx_begin() != TX_OK) {
        tx_log(TX_LOG_ERROR, "[CL_OL_0016] 트랜잭션 시작 실패");
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_SYSERR);
        tx_return(ctx, TX_FAIL, ctx->out);
        return;
    }

    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "update cl_ledger set status = 'S' , upd_ts = now ( ) where key = $1  and status = 'M'", 
	ECPGt_char,(h_key),(long)16,(long)1,(16)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, ECPGt_EORT);}
#line 109 "app/online/cl_ol_0016.pgc"

    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("CL_OL_0016 confirm update");
        tx_abort();
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_SYSERR);
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }
    if (sqlca.sqlerrd[2] == 0) {
        /* 조회~갱신 사이 상태 변동 (경합) → 롤백 후 경고 */
        tx_log(TX_LOG_WARN, "[CL_OL_0016] 확정 대상 소실(경합) key=%s", key);
        tx_abort();
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_INVALID);
        tx_buf_sets(ctx->out, "KEY", key);
        tx_buf_sets(ctx->out, "CONFIRMED", "N");
        tx_buf_sets(ctx->out, "MESSAGE", "확정 대상 상태 변동으로 실패");
        tx_return(ctx, TX_FAIL, ctx->out);
        return;
    }

    tx_commit();

    /* 6. 응답 구성 */
    tx_buf_reset(ctx->out);
    tx_buf_sets(ctx->out, "RESPCODE", RESP_OK);
    tx_buf_sets(ctx->out, "KEY", key);
    tx_buf_sets(ctx->out, "STATUS", CL_ST_SETTLED);
    tx_buf_setlong(ctx->out, "AMOUNT", h_amount);
    tx_buf_sets(ctx->out, "AMOUNTWON", won);
    tx_buf_sets(ctx->out, "CONFIRMED", "Y");
    tx_log(TX_LOG_INFO, "[CL_OL_0016] 마감확정 완료 key=%s M→S 금액=%ld",
           key, h_amount);
    tx_return(ctx, TX_OK, ctx->out);
}
