package cmd

import (
	"axolotl/store"
	"fmt"
	"os"
	"path/filepath"

	"github.com/spf13/cobra"
)

var initCmd = &cobra.Command{
	Use: "init [path]", Short: "Initialize a new database", Args: cobra.MaximumNArgs(1),
	Run: func(cmd *cobra.Command, args []string) {
		var dbPath string
		if len(args) > 0 {
			dbPath = filepath.Join(args[0], "ax.db")
		} else {
			cwd, err := filepath.Abs(".")
			if err != nil {
				fmt.Fprintln(os.Stderr, "failed to get working directory:", err)
				os.Exit(1)
			}
			dbPath = filepath.Join(cwd, ".ax", "ax.db")
		}
		if _, err := os.Stat(dbPath); err == nil {
			fmt.Fprintln(os.Stderr, "database already exists:", dbPath)
			os.Exit(1)
		}
		if err := store.InitSQLiteStore(dbPath); err != nil {
			fmt.Fprintln(os.Stderr, "failed to initialize:", err)
			os.Exit(1)
		}
		PrintAction(cmd.OutOrStdout(), "Created", dbPath, false)
	},
}

func init() { rootCmd.AddCommand(initCmd) }
