package api

import (
	"encoding/json"
	"errors"
	"net/http"

	"gitea.mrixs.me/minecraft-platform/backend/internal/database"
	"github.com/go-chi/chi/v5"
	"github.com/jackc/pgx/v5"
)

type LauncherHandler struct {
	ModpackRepo *database.ModpackRepository
}

func (h *LauncherHandler) GetModpackManifest(w http.ResponseWriter, r *http.Request) {
	modpackName := chi.URLParam(r, "name")
	if modpackName == "" {
		http.Error(w, "Modpack name is required", http.StatusBadRequest)
		return
	}

	manifest, err := h.ModpackRepo.GetModpackManifest(r.Context(), modpackName)
	if err != nil {
		if errors.Is(err, pgx.ErrNoRows) {
			http.Error(w, "Modpack not found or not active", http.StatusNotFound)
			return
		}
		http.Error(w, "Failed to get modpack manifest", http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(manifest)
}

func (h *LauncherHandler) GetModpacksSummary(w http.ResponseWriter, r *http.Request) {
	summaries, err := h.ModpackRepo.GetModpacksSummary(r.Context())
	if err != nil {
		http.Error(w, "Failed to get modpacks summary", http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(summaries)
}
