/*
Copyright © 2024 NAME HERE <EMAIL ADDRESS>
*/
package cmd

import (
	"errors"
	"log"

	"github.com/sirupsen/logrus"
	"github.com/spf13/cobra"

	"dyproxy/.gen/model"
	"dyproxy/.gen/table"
	"dyproxy/providers/db"

	_ "github.com/mattn/go-sqlite3"

	"github.com/go-jet/jet/v2/qrm"
	. "github.com/go-jet/jet/v2/sqlite"
)

// testCmd represents the test command
var testCmd = &cobra.Command{
	Use:   "test",
	Short: "A brief description of your command",
	Run: func(cmd *cobra.Command, argvs []string) {
		db, err := db.Connect("")
		if err != nil {
			log.Fatal(err)
		}
		defer db.Close()

		expert := model.Expert{
			UID:      "123",
			SecUID:   "123",
			ShortID:  "123",
			RealName: "123",
			NickName: "123",
		}

		logrus.Warnf("expert: %+v", expert)
		stmt := table.Expert.SELECT(table.Expert.AllColumns).WHERE(table.Expert.UID.EQ(String(expert.UID)))
		sql, args := stmt.Sql()
		logrus.Debugf("sql: %s args: %+v", sql, args)

		var ui model.Expert
		if err := stmt.Query(db, &ui); err != nil {
			if errors.Is(err, qrm.ErrNoRows) {
				_, err = table.Expert.INSERT(
					table.Expert.UID,
					table.Expert.SecUID,
					table.Expert.ShortID,
					table.Expert.RealName,
					table.Expert.NickName,
				).VALUES(
					String(expert.UID),
					String(expert.SecUID),
					String(expert.ShortID),
					String(expert.RealName),
					String(expert.NickName),
				).Exec(db)
				if err != nil {
					log.Fatal(err)
				}

				log.Println("no rows")
				return
			}
			log.Fatal("123", err)
		}
		log.Println("ID", ui)
	},
}

func init() {
	rootCmd.AddCommand(testCmd)

	// Here you will define your flags and configuration settings.

	// Cobra supports Persistent Flags which will work for this command
	// and all subcommands, e.g.:
	// testCmd.PersistentFlags().String("foo", "", "A help for foo")

	// Cobra supports local flags which will only run when this command
	// is called directly, e.g.:
	// testCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
