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

// common pattern for event-driven architecture
type EventHandler interface {
	Handle(common.EventData, database.DBConnection) error
}

type handlerFunc func(common.EventData, database.DBConnection) error

func (f handlerFunc) Handle(data common.EventData, dbconn database.DBConnection) error {
	return f(data, dbconn)
}

// EventDispatcher routes events to their handlers.
type EventDispatcher struct {
	handlers map[string]EventHandler
}

func NewEventDispatcher() *EventDispatcher {
	return &EventDispatcher{
		handlers: make(map[string]EventHandler),
	}
}

func (d *EventDispatcher) Register(eventName common.EventName, handler EventHandler) {
	d.handlers[string(eventName)] = handler
}

func (d *EventDispatcher) Dispatch(eventName common.EventName, data common.EventData, dbconn database.DBConnection) error {
	if handler, ok := d.handlers[string(eventName)]; ok {
		return handler.Handle(data, dbconn)
	}
	return fmt.Errorf("no handler registered for event: %s", eventName)
}

// Concrete handlers using handlerFunc
var (
	runHandler            = handlerFunc(processRun)
	timeoutHandler        = handlerFunc(processJobnetTimeout)
	delayStartHandler     = handlerFunc(processDelayStart)
	scheduleDeleteHandler = handlerFunc(processScheduleDelete)
	stopAndEndHandler     = handlerFunc(processEnd)
	iconRerunHandler      = handlerFunc(processIconStatusSync)
	runErrHandler         = handlerFunc(processRunErr)
	scheduleUpdateHandler = handlerFunc(processScheduleUpdate)
	holdHandler           = handlerFunc(processHold)
	unHoldHandler         = handlerFunc(processRelease)
)
