package app

import (
	"myexampleapp/pkg/zgen/apigen"

	anclax_app "github.com/cloudcarver/anclax/pkg/app"
	"github.com/cloudcarver/anclax/pkg/taskcore/worker"
	"github.com/gofiber/fiber/v2"
)

type App struct {
	AnclaxApp *anclax_app.Application
}

func (a *App) Start() error {
	return a.AnclaxApp.Start()
}

func (a *App) Close() {
	a.AnclaxApp.Close()
}

type Plugin struct {
	serverInterface apigen.ServerInterface
	validator       apigen.Validator
	taskHandler     worker.TaskHandler
}

func NewPlugin(serverInterface apigen.ServerInterface, validator apigen.Validator, taskHandler worker.TaskHandler) anclax_app.Plugin {
	return &Plugin{
		serverInterface: serverInterface,
		validator:       validator,
		taskHandler:     taskHandler,
	}
}

func (p *Plugin) PlugTo(anclaxApp *anclax_app.Application) error {
	p.plugToFiberApp(anclaxApp.GetServer().GetApp())
	p.plugToWorker(anclaxApp.GetWorker())
	return nil
}

func (p *Plugin) plugToFiberApp(fiberApp *fiber.App) {
	apigen.RegisterHandlersWithOptions(fiberApp, apigen.NewXMiddleware(p.serverInterface, p.validator), apigen.FiberServerOptions{
		BaseURL:     "/api/v1",
		Middlewares: []apigen.MiddlewareFunc{},
	})
}

func (p *Plugin) plugToWorker(worker worker.WorkerInterface) {
	worker.RegisterTaskHandler(p.taskHandler)
}
