package cli

import (
	"encoding/json"
	"fmt"
	"log"
	"opencatd-open/internal/model"
	"opencatd-open/pkg/store"
	"os"
	"strings"

	"github.com/duke-git/lancet/v2/fileutil"

	"github.com/google/uuid"
	"github.com/spf13/cobra"
)

var LoadCmd = &cobra.Command{
	Use:   "load",
	Short: "import user.json -> db",
	Long:  "\nimport user.json -> db",
	Run: func(cmd *cobra.Command, args []string) {
		db := store.GetDB()
		var cont int64
		if err := db.Model(model.User{}).Count(&cont).Error; err != nil {
			fmt.Println(err)
			return
		}
		if cont == 0 {
			fmt.Println("创建管理员之后再操作")
		}
		if !fileutil.IsExist("./db/user.json") {
			log.Fatalln("404! user.json is not found.")
			return
		}
		file, err := os.Open("./db/user.json")
		if err != nil {
			fmt.Println("Error opening file:", err)
			return
		}
		defer file.Close()

		var usermap []map[string]string

		if err := json.NewDecoder(file).Decode(&usermap); err != nil {
			fmt.Println("解析文件失败:", err)
			return
		}
		for _, um := range usermap {
			var name string
			if um["username"] != "" {
				name = um["name"]
			} else if um["name"] == "" {
				name = um["username"]
			} else {
				fmt.Println("获取不到数据")
				continue
			}
			var user = model.User{
				Username: name,
				Name:     name,
				Tokens: []model.Token{
					{
						Name: "default",
						Key:  "sk-team-" + strings.ReplaceAll(uuid.New().String(), "-", ""),
					},
					{
						Name: name,
						Key:  um["token"],
					},
				},
			}
			if err := db.Create(&user).Error; err != nil {
				fmt.Printf("\nCreate User %s Error:%s", user.Username, err)
			}
		}

	},
}

var SaveCmd = &cobra.Command{
	Use:   "save",
	Short: "backup user info -> user.json",
	Run: func(cmd *cobra.Command, args []string) {

	},
}

func init() {
	// SaveCmd.Flags().StringP("user", "u", "", "Save User")
}
