package handlers

import (
	"encoding/json"
	"gemini-balancer/internal/errors"
	"gemini-balancer/internal/response"
	"gemini-balancer/internal/task"

	"github.com/sirupsen/logrus"

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

type TaskHandler struct {
	taskService *task.Task
	logger      *logrus.Entry
}

func NewTaskHandler(taskService *task.Task, logger *logrus.Logger) *TaskHandler {
	return &TaskHandler{
		taskService: taskService,
		logger:      logger.WithField("component", "TaskHandler📦"),
	}

}

// GetTaskStatus
// GET /admin/tasks/:id
func (h *TaskHandler) GetTaskStatus(c *gin.Context) {
	taskID := c.Param("id")
	if taskID == "" {
		response.Error(c, errors.NewAPIError(errors.ErrBadRequest, "task ID is required"))
		return
	}

	taskStatus, err := h.taskService.GetStatus(c.Request.Context(), taskID)
	if err != nil {
		// TODO 可以根据 service 层返回的具体错误类型进行更精细的处理
		response.Error(c, errors.NewAPIError(errors.ErrResourceNotFound, err.Error()))
		return
	}
	// [探針] 在返回給前端前，打印從存儲中讀取並解析後的 status 對象
	loggerWithTaskID := h.logger.WithField("task_id", taskID)
	loggerWithTaskID.Debugf("Status read from store, ABOUT TO BE SENT to frontend: %+v", taskStatus)
	// [探針] 手動序列化並打印
	if h.logger.Logger.IsLevelEnabled(logrus.DebugLevel) {
		jsonData, _ := json.Marshal(taskStatus)
		loggerWithTaskID.Debugf("Manually marshalled JSON to be sent to frontend: %s", string(jsonData))
	}
	response.Success(c, taskStatus)
}
