package task

import (
	"context"
	"net/http"
	"strings"

	"github.com/tidbcloud/AgentTeam/internal/api"
	"github.com/tidbcloud/AgentTeam/internal/api/dto/converter"
	"github.com/tidbcloud/AgentTeam/internal/store/agent"
)

// TaskReviewContextStore is the human Task read boundary for review contexts.
// The store must authorize the canonical Task before returning any rows.
type TaskReviewContextStore interface {
	ListReviewContextsForTaskID(ctx context.Context, userID string, workspaceID string, taskID string) ([]agent.ReviewContext, error)
}

// TaskReviewContextHandler serves review contexts attached to a canonical Task.
type TaskReviewContextHandler struct {
	store TaskReviewContextStore
}

func (h *TaskReviewContextHandler) List(r api.WorkspaceScopedRequest) (api.Response, error) {
	taskID := strings.TrimSpace(r.Gin.Param("taskId"))
	if taskID == "" {
		return api.Response{}, api.NewHTTPError(http.StatusBadRequest, "taskId is required")
	}
	if h.store == nil {
		return api.Response{}, api.NewHTTPError(http.StatusInternalServerError, "Internal server error")
	}
	contexts, err := h.store.ListReviewContextsForTaskID(r.Context(), r.UserID(), r.WorkspaceID(), taskID)
	if err != nil {
		return api.Response{}, err
	}
	return api.OK(map[string]any{"contexts": converter.ToReviewContexts(contexts)}), nil
}
