/*
** 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 main

import (
	"fmt"
	"strings"

	"jobarranger2/src/libs/golibs/builder"
	"jobarranger2/src/libs/golibs/common"
	"jobarranger2/src/libs/golibs/database"
	"jobarranger2/src/libs/golibs/event"
	"jobarranger2/src/libs/golibs/utils"
)

func processRunErr(jobnetPayload common.EventData, dbconn database.DBConnection) error {
	funcname := "processRunErr"
	JobnetRunLogger.JaLog("JAJOBNETRUN400001", funcname)
	queries := []common.ParameterizedQuery{}

	jobnetRunData, err := getJobnetRunData(jobnetPayload.NextProcess.Data)
	if err != nil {
		return err
	}

	isSubJobnet, _, err := IsSubJobnet(dbconn, jobnetRunData.InnerJobnetId)
	if err != nil {
		return fmt.Errorf("%s", err.Error())
	}
	parts := []string{jobnetRunData.JobnetID, jobnetRunData.JobId}
	errorJobId := strings.Join(parts, "/")

	var nextEventData common.EventData
	queries = jaSetStatusJobnet(jobnetRunData.InnerJobnetId, common.StatusRunErr, -1, 1, queries...)
	queries = jaSetJobStatusSummary(jobnetRunData.InnerJobnetId, JA_SUMMARY_JOB_STATUS_ERROR, queries...)
	queries = jaSetRunningJobIdSummary(jobnetRunData.InnerJobnetId, errorJobId, queries...)
	if isSubJobnet {
		nextEventData = prepareNextEventData(
			common.EventSubJobnetStatusChange,
			common.FlowManagerProcess,
			common.FlowProcessData{
				InnerJobnetId: jobnetRunData.InnerJobnetId,
				Status:        common.StatusRunErr,
				JobnetId:      jobnetRunData.JobnetID,
			},
			queries,
		)
	} else {
		nextEventData = prepareNextEventData(
			common.EventJobnetStatusChange,
			common.DBSyncerManagerProcess,
			map[string]any{},
			queries,
		)
	}
	sqlCond := builder.NewSQLCondition(
		fmt.Sprintf("select status from ja_2_run_jobnet_table where inner_jobnet_id = %d", jobnetRunData.InnerJobnetId),
	).
		AddCondition(
			builder.NewCondition("ignore").
				Field("status", common.OpEq, common.StatusEndErr).
				Build(),
		).
		DefaultAction(common.ActionExec). // move to error folder
		Build()
	nextEventData.SQLConditions = []common.SQLCondition{sqlCond}

	JobnetRunLogger.JaLog("JAJOBNETRUN400009", nextEventData)
	err = event.CreateNextEvent(nextEventData, jobnetRunData.InnerJobnetId, jobnetRunData.JobnetID, jobnetRunData.InnerJobId)
	if err != nil {
		return fmt.Errorf("%s", err.Error())
	}

	//first move the incoming file from flow manager
	currentFilePath := jobnetPayload.Transfer.Files[0].Source
	err = utils.MoveToSubFolder(currentFilePath, END)
	if err != nil {
		return fmt.Errorf("%s", err.Error())
	}
	JobnetRunLogger.JaLog("JAJOBNETRUN400002", funcname)
	return nil
}
