package cmd

import (
	"axolotl/serve"
	"axolotl/service"
	"axolotl/store"
	"fmt"
	"net/http"
	"os"

	"github.com/spf13/cobra"
)

var serveCmd = &cobra.Command{
	Use:   "serve",
	Short: "Start the JSON API server",
	Run: func(cmd *cobra.Command, args []string) {
		sc := cfg.GetServerConfig()
		addr := fmt.Sprintf("%s:%d", sc.Host, sc.Port)

		var oidcCfg *store.OIDCConfig
		if oc, ok := cfg.GetOIDCConfig(); ok {
			oidcCfg = oc
		}

		handler, err := serve.New(func(user string) (service.NodeService, error) {
			if user == "" {
				return nil, fmt.Errorf("user is required")
			}
			st, err := store.FindOrInitSQLiteStore()
			if err != nil {
				return nil, err
			}
			return service.NewLocalNodeService(st, user), nil
		}, oidcCfg)
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(1)
		}
		fmt.Fprintf(os.Stdout, "listening on %s\n", addr)
		if err := http.ListenAndServe(addr, handler); err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(1)
		}
	},
}

func init() {
	rootCmd.AddCommand(serveCmd)
}
