package httpapi

import (
	"context"
	"net/http"

	"github.com/easyai/easyai-ai-gateway/apps/api/internal/clients"
	"github.com/easyai/easyai-ai-gateway/apps/api/internal/store"
)

func (s *Server) hydrateTaskResult(ctx context.Context, task store.GatewayTask) (store.GatewayTask, error) {
	if task.Status != "succeeded" || len(task.Result) == 0 {
		return task, nil
	}
	result, err := s.runner.ProjectTaskResultURLs(ctx, task.ID, task.Result)
	if err != nil {
		return store.GatewayTask{}, err
	}
	task.Result = result
	return task, nil
}

func writeStoredBinaryResultError(w http.ResponseWriter, err error) {
	status := statusFromRunError(err)
	code := clients.ErrorCode(err)
	if code == "" {
		code = "binary_result_corrupted"
	}
	writeError(w, status, err.Error(), code)
}
