/*
** 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"
	"jobarranger2/src/libs/golibs/common"
	"jobarranger2/src/libs/golibs/config_reader/server"
	"jobarranger2/src/libs/golibs/database"
	"jobarranger2/src/libs/golibs/event"
	"jobarranger2/src/libs/golibs/utils"
	"path/filepath"
)

func processScheduleUpdate(jobnetPayload common.EventData, dbconn database.DBConnection) error {
	funcname := "processScheduleUpdate"
	JobnetRunLogger.JaLog("JAJOBNETRUN400001", funcname)

	jobnetRunData, err := getJobnetRunData(jobnetPayload.NextProcess.Data)
	if err != nil {
		return fmt.Errorf("get jobnetRundata failed %w", err)
	}

	queries := []common.ParameterizedQuery{}
	queries = jaSetScheduledTime(jobnetRunData.InnerJobnetId, jobnetRunData.ScheduledTime, queries...)

	//stop the running go routine
	GetScheduleJobnets().Remove(jobnetRunData.InnerJobnetId)
	JobnetRunLogger.JaLog("JAJOBNETRUN400021", jobnetRunData.InnerJobnetId)

	currentFilePath := jobnetPayload.Transfer.Files[0].Source

	nextEventData := prepareNextEventData(
		common.EventScheduleUpdateDBSync,
		common.DBSyncerManagerProcess,
		map[string]any{},
		queries,
	)

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

	err = utils.MoveToSubFolder(currentFilePath, END)
	if err != nil {
		return fmt.Errorf("moveFile from current %s to %s failed : %s", currentFilePath, END, err.Error())
	}

	fileName, err := findFileByInnerJobnetID(JOBNETMANAGER_IN_DIR, jobnetRunData.InnerJobnetId)
	if err != nil {
		return fmt.Errorf("find file in %s failed: %w", JOBNETMANAGER_IN_DIR, err)
	}

	sockFilePathFull := filepath.Join(server.Options.UnixSockParentDir, common.JobnetManagerSockFile)
	return updateTransactionFile(
		jobnetRunData.InnerJobnetId,
		jobnetRunData.InnerJobId,
		string(common.JobnetManagerProcess),
		sockFilePathFull,
		fileName,
		func(data *common.JobnetRunData) {
			data.ScheduledTime = jobnetRunData.ScheduledTime
		},
	)
}
