/*
** 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/database"
	"jobarranger2/src/libs/golibs/event"
	"jobarranger2/src/libs/golibs/utils"
)

func processScheduleDelete(jobnetPayload common.EventData, dbconn database.DBConnection) error {
	funcname := "processScheduleDelete"
	JobnetRunLogger.JaLog("JAJOBNETRUN400001", funcname)
	jobnetRunData, err := getJobnetRunData(jobnetPayload.NextProcess.Data)
	if err != nil {
		return fmt.Errorf("get jobnetRundata failed %w", err)
	}

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

	// 1. Find and handle the original .json file
	if err := moveFilesToEndForInnerJobnet(jobnetRunData.InnerJobnetId, JOBNETMANAGER_IN_DIR); err != nil {
		return err
	}

	// 2. Handle file with schedule delete event
	if len(jobnetPayload.Transfer.Files) == 0 {
		return fmt.Errorf("no transfer files found")
	}

	//create query for json
	//delete the scheduled that
	queries := []common.ParameterizedQuery{}
	queries = jaStatusScheduleJobnetDelete(jobnetRunData.InnerJobnetId, queries...)

	// Data preparation for json file
	nextEvent := prepareNextEventData(
		common.EventScheduleDeleteDBSync,
		common.DBSyncerManagerProcess,
		map[string]interface{}{},
		queries,
	)

	err = event.CreateNextEvent(nextEvent, jobnetRunData.InnerJobnetId, jobnetRunData.JobnetID, jobnetRunData.InnerJobId)
	if err != nil {
		return fmt.Errorf("%v", err)
	}
	JobnetRunLogger.JaLog("JAJOBNETRUN000011")

	transferSource := jobnetPayload.Transfer.Files[0].Source
	err = utils.MoveToSubFolder(transferSource, END)
	if err != nil {
		return fmt.Errorf("%s", err.Error())
	}
	JobnetRunLogger.JaLog("JAJOBNETRUN400002", funcname)
	return nil
}
