package cli

import (
	"fmt"

	"banger/internal/installmeta"
	"banger/internal/paths"

	"github.com/spf13/cobra"
)

func (d *deps) newDaemonCommand() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "daemon",
		Short: "Manage the installed banger services",
		RunE:  helpNoArgs,
	}
	cmd.AddCommand(
		&cobra.Command{
			Use:   "status",
			Short: "Show owner-daemon and root-helper status",
			Args:  noArgsUsage("usage: banger daemon status"),
			RunE: func(cmd *cobra.Command, args []string) error {
				return d.runSystemStatus(cmd.Context(), cmd.OutOrStdout())
			},
		},
		&cobra.Command{
			Use:   "stop",
			Short: "Stop the installed banger services",
			Args:  noArgsUsage("usage: banger daemon stop"),
			RunE: func(cmd *cobra.Command, args []string) error {
				if err := requireRoot(); err != nil {
					return err
				}
				if err := d.runSystemctl(cmd.Context(), "stop", installmeta.DefaultService, installmeta.DefaultRootHelperService); err != nil {
					return err
				}
				_, err := fmt.Fprintln(cmd.OutOrStdout(), "stopped")
				return err
			},
		},
		&cobra.Command{
			Use:   "socket",
			Short: "Print the daemon socket path",
			Args:  noArgsUsage("usage: banger daemon socket"),
			RunE: func(cmd *cobra.Command, args []string) error {
				layout := paths.ResolveSystem()
				var err error
				_, err = fmt.Fprintln(cmd.OutOrStdout(), layout.SocketPath)
				return err
			},
		},
	)
	return cmd
}
