package ipapi

import (
	"context"
	"os"

	"git.eeqj.de/sneak/ipapi/internal/config"
	"git.eeqj.de/sneak/ipapi/internal/database"
	"git.eeqj.de/sneak/ipapi/internal/http"
	"git.eeqj.de/sneak/ipapi/internal/log"
	"git.eeqj.de/sneak/ipapi/internal/state"
	"github.com/spf13/cobra"
	"go.uber.org/fx"
)

const defaultConfigFile = "/etc/ipapi/config.yml"

func daemonCmd() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "daemon",
		Short: "Run the IP API daemon",
		Long:  `Start the IP API HTTP server that provides GeoIP information.`,
		RunE: func(_ *cobra.Command, _ []string) error {
			configFile := getConfigFile()

			app := fx.New(
				fx.Provide(
					func() (*config.Config, error) {
						return config.New(configFile)
					},
					log.New,
					state.New,
					database.New,
					http.NewServer,
					http.NewRouterWrapper,
					New,
				),
				fx.Invoke(func(lc fx.Lifecycle, ipapi *IPAPI) {
					lc.Append(fx.Hook{
						OnStart: func(ctx context.Context) error {
							return ipapi.Start(ctx)
						},
						OnStop: func(ctx context.Context) error {
							return ipapi.Stop(ctx)
						},
					})
				}),
			)

			app.Run()

			return nil
		},
	}

	return cmd
}

func getConfigFile() string {
	configFile := os.Getenv("IP_API_CONFIG_FILE")
	if configFile == "" {
		return defaultConfigFile
	}

	return configFile
}
