package command

import (
	"fmt"
	"strings"

	"github.com/memohai/memoh/internal/settings"
)

func (h *Handler) buildBrowserGroup() *CommandGroup {
	g := newCommandGroup("browser", "Manage browser context")
	g.Register(SubCommand{
		Name:  "list",
		Usage: "list - List all browser contexts",
		Handler: func(cc CommandContext) (string, error) {
			items, err := h.browserCtxService.List(cc.Ctx)
			if err != nil {
				return "", err
			}
			if len(items) == 0 {
				return "No browser contexts found.", nil
			}
			records := make([][]kv, 0, len(items))
			for _, item := range items {
				records = append(records, []kv{
					{"Name", item.Name},
				})
			}
			return formatItems(records), nil
		},
	})
	g.Register(SubCommand{
		Name:    "set",
		Usage:   "set <name> - Set the browser context for this bot",
		IsWrite: true,
		Handler: func(cc CommandContext) (string, error) {
			if len(cc.Args) < 1 {
				return "Usage: /browser set <name>", nil
			}
			name := cc.Args[0]
			items, err := h.browserCtxService.List(cc.Ctx)
			if err != nil {
				return "", err
			}
			for _, item := range items {
				if strings.EqualFold(item.Name, name) {
					_, err := h.settingsService.UpsertBot(cc.Ctx, cc.BotID, settings.UpsertRequest{
						BrowserContextID: item.ID,
					})
					if err != nil {
						return "", err
					}
					return fmt.Sprintf("Browser context set to %q.", item.Name), nil
				}
			}
			return fmt.Sprintf("Browser context %q not found.", name), nil
		},
	})
	return g
}
