package handler

import (
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
)

func BattleHandler(c *gin.Context, executor CommandExecutor) {
	turn := c.Param("turn")
	t, err := strconv.Atoi(turn)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	if t < 0 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "turn number can't be negative"})
		return
	}
	id := c.Param("uuid")
	battleID, err := uuid.Parse(id)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	r, exists, err := executor.FetchBattle(uint(t), battleID)
	if errorResponse(c, err) {
		return
	}
	if !exists {
		c.JSON(http.StatusNotFound, gin.H{"error": "unknown battle"})
		return
	}
	c.JSON(http.StatusOK, r)
}
