package api

import (
	"encoding/json"
	"net/http"
	"os/exec"
)

func (s *Server) handleTerminal(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		writeError(w, "POST only", http.StatusMethodNotAllowed)
		return
	}
	var body struct {
		Command string `json:"command"`
		Cwd     string `json:"cwd"`
	}
	if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
		writeError(w, err.Error(), http.StatusBadRequest)
		return
	}
	if body.Command == "" {
		writeError(w, "no command", http.StatusBadRequest)
		return
	}

	shell := detectShell()

	cmd := exec.Command(shell, "-c", body.Command)
	if body.Cwd != "" {
		cmd.Dir = body.Cwd
	}
	out, err := cmd.CombinedOutput()

	type termResult struct {
		Output string `json:"output"`
		Error  string `json:"error,omitempty"`
	}
	result := termResult{Output: string(out)}
	if err != nil {
		result.Error = err.Error()
	}
	writeJSON(w, result)
}
