package custom

import (
	"pocketbase/custom/cloudflare"
	"pocketbase/custom/gtm"
	"pocketbase/custom/mail"
	"pocketbase/custom/manifest"
	"pocketbase/custom/proxy"
	"pocketbase/custom/seo"
	"pocketbase/custom/supervise"
	"pocketbase/custom/version"
	webpconverter "pocketbase/custom/webpConverter"

	"github.com/pocketbase/pocketbase"
	"github.com/pocketbase/pocketbase/core"
)

func LoadCustomCode(app *pocketbase.PocketBase, se *core.ServeEvent) error {

	// include supervised subprocess if command provided
	supervise.ServeSubprocessSupervisor(app, se)

	// include serving js code from cloudflare
	cloudflare.ServeTurnstilleCaptchaJS(app, se)

	// include sending emails service
	mail.ServeMailSender(app, se)

	// include robots.txt endpoint
	seo.ServeRobotsTxt(app, se)

	// include feeds endpoint
	seo.ServeFeeds(app, se)
	seo.ServeFeedsIndex(app, se)

	// include proxy to serve nuxt app
	proxy.ServeProxyPassingToNuxt(app, se)

	// create endpoint to serve version information
	version.ServeVersionInfo(app, se)

	// include endpoint to server GTM script
	gtm.ServeTagMangerJS(app, se)

	// include endpoint serving manifest
	manifest.ServeManifst(app, se)

	return nil
}

func ExtendApp(app *pocketbase.PocketBase) *pocketbase.PocketBase {
	app.RootCmd.PersistentFlags().String("proxy", "", "inner proxy target")
	app.RootCmd.PersistentFlags().String("subcommand", "", "provide command with params like cli that will be executed and supervised by main process")

	// include webp converter
	app.OnRecordCreate().Bind(webpconverter.CreateEventHandler(app))
	app.OnRecordUpdate().Bind(webpconverter.CreateEventHandler(app))
	app.OnFileDownloadRequest().Bind(webpconverter.ThumbEventHandler(app))

	return app
}
