package handlers

import (
	"encoding/json"
	"html/template"
	"mc-monitor/middleware"
	"mc-monitor/models"
	"net/http"

	"github.com/gorilla/mux"
)

type ServerPageData struct {
	Username string
	Server   models.ServerInfo
}

func ServerPageHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	id := vars["id"]

	server, ok := models.GetServerByID(id)
	if !ok {
		http.NotFound(w, r)
		return
	}

	data := ServerPageData{
		Username: getUsername(r),
		Server:   server,
	}
	
	tmpl := template.Must(template.ParseFiles("templates/server.html"))
	tmpl.Execute(w, data)
}

func ServerActionHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	id := vars["id"]
	action := vars["action"]

	if !models.ServerExists(id) {
		http.NotFound(w, r)
		return
	}

	switch action {
	case "stop":
		models.SetServerStatus(id, "stopped")
	case "start":
		models.SetServerStatus(id, "online")
	case "restart":
		models.SetServerStatus(id, "restarting")
		models.ScheduleServerOnline(id, 6)
	default:
		http.Error(w, "Unsupported action", http.StatusBadRequest)
		return
	}

	result := map[string]string{
		"status":  "ok",
		"message": "Команда принята: " + action,
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(result)
}

func getUsername(r *http.Request) string {
	session, ok := middleware.GetSession(r)
	if ok {
		return session.Username
	}
	return "operator"
}
