package cmd

import (
	"axolotl/service"
	"fmt"
	"os"
	"os/exec"

	"github.com/spf13/cobra"
)

var editCmd = &cobra.Command{
	Use: "edit <id>", Short: "Edit node content in $EDITOR", Args: cobra.ExactArgs(1),
	Run: func(cmd *cobra.Command, args []string) {
		svc, err := getNodeService()
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			return
		}

		n, err := svc.GetByID(args[0])
		if err != nil {
			fmt.Fprintln(os.Stderr, "node not found:", args[0])
			return
		}

		tmp, err := os.CreateTemp("", "ax-*.md")
		if err != nil {
			fmt.Fprintln(os.Stderr, "failed to create temp file:", err)
			return
		}
		tmp.WriteString(n.Content)
		tmp.Close()
		defer os.Remove(tmp.Name())

		c := exec.Command(cfg.GetEditor(), tmp.Name())
		c.Stdin, c.Stdout, c.Stderr = os.Stdin, os.Stdout, os.Stderr
		if err := c.Run(); err != nil {
			fmt.Fprintln(os.Stderr, "editor failed:", err)
			return
		}

		content, err := os.ReadFile(tmp.Name())
		if err != nil {
			fmt.Fprintln(os.Stderr, "failed to read temp file:", err)
			return
		}
		s := string(content)
		n, err = svc.Update(args[0], service.UpdateInput{Content: &s})
		if err != nil {
			fmt.Fprintln(os.Stderr, "failed to update:", err)
			return
		}
		PrintNode(cmd.OutOrStdout(), svc, n, jsonFlag)
	},
}

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