/*
** Job Arranger for ZABBIX
** Copyright (C) 2025 Daiwa Institute of Research Ltd. All Rights Reserved.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
**/
package utils

import (
	"jobarranger2/src/libs/golibs/common"
	"jobarranger2/src/libs/golibs/config_reader/server"
	"jobarranger2/src/libs/golibs/database"
	"jobarranger2/src/libs/golibs/logger/logger"
	"os"
	"runtime/debug"
	"strings"
	"time"
)

// Check DB down and DB CriticalErrors
func CheckDBCriticalError(dbConn database.DBConnection, query string) {
	var dbErrExitCodes, dbSyncRetryCodes string

	errCode := dbConn.DBErrCode()
	errMsg := dbConn.DBErrMessage()
	dbType := server.Options.DBType

	// Check db down
	if !dbConn.IsAlive() {
		logger.JaLog("JADBERROR200001", logger.Logging{}, string(debug.Stack()))
		os.Exit(1)
	}

	// Check db critical errors
	switch dbType {
	case database.PostgresDBType:
		dbErrExitCodes = server.Options.PostgresDBRetryCodes
		dbSyncRetryCodes = server.Options.PostgresDBSyncRetryCodes
	case database.MysqlDBType:
		dbErrExitCodes = server.Options.MysqlDBRetryCodes
		dbSyncRetryCodes = server.Options.MysqlDBSyncRetryCodes
	case database.MariaDBType:
		dbErrExitCodes = server.Options.MariaDBRetryCodes
		dbSyncRetryCodes = server.Options.MariaDBSyncRetryCodes
	}

	errCode = strings.TrimSpace(errCode)

	// for dbsync retry error, do not exit but return
	if common.Manager.Name == common.DBSyncerManagerProcess {
		for retryCode := range strings.SplitSeq(dbSyncRetryCodes, ",") {
			if strings.TrimSpace(retryCode) == errCode {
				logger.JaLog("JADBERROR300002", logger.Logging{}, errCode, errMsg, query)
				return
			}
		}
	}

	for exitCode := range strings.SplitSeq(dbErrExitCodes, ",") {
		if strings.TrimSpace(exitCode) == errCode {
			logger.JaLog("JADBERROR200002", logger.Logging{}, errCode, errMsg, query, string(debug.Stack()))
			os.Exit(1)
		}
	}
}

func CheckSlowQuery(startTime time.Time, sql string) {
	if server.Options.LogSlowQueries != 0 {
		elapsed := time.Since(startTime).Seconds()
		slowQueryThreshold := float64(server.Options.LogSlowQueries) / 1000.0

		if elapsed > slowQueryThreshold {
			log := logger.Logging{}

			log.JaLog("JADBERROR300001", elapsed, sql)
		}
	}
}
