package handlers

import (
	"encoding/json"
	"io"
	"mc-monitor/models"
	"net/http"
	"time"
)

type ModRequest struct {
	ServerID string `json:"server_id"`
	URL      string `json:"url"`
}

type ModResponse struct {
	Status  string `json:"status"`
	Preview string `json:"preview"`
	Message string `json:"message,omitempty"`
}

func AddModsHandler(w http.ResponseWriter, r *http.Request) {
	var req ModRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		writeModError(w, http.StatusBadRequest, "Invalid JSON")
		return
	}

	if req.URL == "" {
		writeModError(w, http.StatusBadRequest, "Missing url")
		return
	}

	if req.ServerID != "" && !models.ServerExists(req.ServerID) {
		writeModError(w, http.StatusBadRequest, "Unknown server")
		return
	}

	client := &http.Client{Timeout: 4 * time.Second}
	resp, err := client.Get(req.URL)
	if err != nil {
		writeModError(w, http.StatusBadGateway, "Failed to fetch mod")
		return
	}
	defer resp.Body.Close()

	body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))

	result := ModResponse{
		Status:  "loaded",
		Preview: string(body),
	}
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(result)
}

func writeModError(w http.ResponseWriter, status int, message string) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	json.NewEncoder(w).Encode(ModResponse{
		Status:  "error",
		Message: message,
	})
}
