package api

import (
	"errors"
	"log/slog"
	"net/http"

	"github.com/go-chi/chi/v5"

	"github.com/alexei/tinyforge/internal/store"
)

// getInstanceStats handles GET /api/projects/{id}/stages/{stage}/instances/{iid}/stats.
// {iid} is the container row ID (same UUID as the legacy instance ID).
func (s *Server) getInstanceStats(w http.ResponseWriter, r *http.Request) {
	id := chi.URLParam(r, "iid")

	c, err := s.store.GetContainerByID(id)
	if err != nil {
		if errors.Is(err, store.ErrNotFound) {
			respondNotFound(w, "container")
			return
		}
		slog.Error("failed to get container", "id", id, "error", err)
		respondError(w, http.StatusInternalServerError, "failed to get container")
		return
	}

	if c.ContainerID == "" {
		respondError(w, http.StatusBadRequest, "container row has no docker container bound")
		return
	}

	stats, err := s.docker.GetContainerStats(r.Context(), c.ContainerID)
	if err != nil {
		slog.Error("failed to get container stats", "container_id", c.ContainerID, "error", err)
		respondError(w, http.StatusInternalServerError, "failed to get container stats")
		return
	}

	respondJSON(w, http.StatusOK, stats)
}
