/*
** 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"
	"path/filepath"

	"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"
)

// processRelease handles the "release" event by updating the database state and preparing the jobnetPayload file.
func processRelease(jobnetPayload common.EventData, dbconn database.DBConnection) error {
	funcname := "processRelease"
	JobnetRunLogger.JaLog("JAJOBNETRUN400001", funcname)

	sourceFileName := jobnetPayload.Transfer.Files[0].Source
	jobnetRunData, ok := jobnetPayload.NextProcess.Data.(common.JobnetRunData)
	if !ok {
		return fmt.Errorf("type assertion to JobnetRunData failed")
	}
	JobnetRunLogger.JaLog("JAJOBNETRUN000010")
	queries := []common.ParameterizedQuery{}
	queries = jaStatusJobnetReleaseSummary(jobnetRunData.InnerJobnetId, queries...)

	jobnetPayload = prepareNextEventData(
		common.EventScheduleReleaseDBSync,
		common.DBSyncerManagerProcess,
		map[string]any{},
		queries,
	)

	err := event.CreateNextEvent(jobnetPayload, jobnetRunData.InnerJobnetId, jobnetRunData.JobnetID, jobnetRunData.InnerJobId)
	if err != nil {
		return fmt.Errorf("%v", err)
	}

	err = utils.MoveToSubFolder(sourceFileName, END)
	if err != nil {
		return fmt.Errorf("%s", err.Error())
	}

	dirs := []string{
		JOBNETMANAGER_WAIT_DIR,
		JOBNETMANAGER_IN_DIR,
	}
	fileName, err := findJobnetFileInDirs(dirs, jobnetRunData.InnerJobnetId)
	if err != nil {
		return err
	}

	if fileName == "" {
		// nothing to move
		return fmt.Errorf("find not found under /in and /wait folder")
	}

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