/*
 * Copyright 2026 Oleg Borodin <onborodin@gmail.com>
 *
 * This work is published and licensed under a Creative Commons
 * Attribution-NonCommercial-NoDerivatives 4.0 International License.
 *
 * Distribution of this work is permitted, but commercial use and
 * modifications are strictly prohibited.
 */
package starter

import (
	"os"
	"path/filepath"

	"helmet/app/server"
	"helmet/pkg/client"

	"github.com/spf13/cobra"
)

type Starter struct {
	runAsDaemon bool
	port        uint32
	cmd         *cobra.Command
	srv         *server.Server
}

func NewStarter() *Starter {
	execName := filepath.Base(os.Args[0])
	sta := &Starter{}
	cmd := &cobra.Command{
		Use:          execName,
		Short:        "\nProxy service",
		SilenceUsage: true,
		RunE:         sta.run,
	}
	cmd.CompletionOptions.DisableDefaultCmd = true
	cmd.Flags().BoolVarP(&sta.runAsDaemon, "asDaemon", "D", false, "Run service as daemon")
	cmd.Flags().Uint32VarP(&sta.port, "port", "P", client.DefaultServicePort, "Service port")

	sta.cmd = cmd
	return sta
}

func (sta *Starter) GetCmd() *cobra.Command {
	return sta.cmd
}

func (sta *Starter) run(cmd *cobra.Command, args []string) error {
	var err error
	srv, err := server.NewServer()
	if err != nil {
		return err
	}
	err = srv.Configure()
	if err != nil {
		return err
	}
	srv.Config().AsDaemon = sta.runAsDaemon
	srv.Config().Service.Port = sta.port

	err = srv.Daemonize()
	if err != nil {
		return err
	}
	err = srv.Build()
	if err != nil {
		return err
	}
	err = srv.Run()
	if err != nil {
		return err
	}
	sta.srv = srv
	return err
}

func (sta *Starter) Exec() error {
	return sta.cmd.Execute()
}
