package workspace

import (
	"net/http"

	"github.com/tidbcloud/AgentTeam/internal/api"
	"github.com/tidbcloud/AgentTeam/internal/api/dto"
	"github.com/tidbcloud/AgentTeam/internal/api/dto/converter"

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

// VisibleProviders handles GET /api/v1/workspaces/:workspaceId/providers.
// It returns the org-managed providers visible to the current workspace.
func (handler *WorkspaceHandler) VisibleProviders(ctx *gin.Context) {
	currentWorkspace, ok := api.CurrentWorkspaceFromContext(ctx)
	if !ok {
		api.Error(ctx, http.StatusBadRequest, "No workspace selected")
		return
	}

	orgs, ok := handler.organizationProvider()
	if !ok {
		ctx.JSON(http.StatusOK, []dto.OrgProviderView{})
		return
	}

	providers, err := orgs.ListVisibleOrganizationProvidersForWorkspace(ctx.Request.Context(), currentWorkspace.WorkspaceID)
	if err != nil {
		api.StoreError(ctx, err)
		return
	}
	response := converter.ToOrgProviderViews(providers)
	if response == nil {
		response = []dto.OrgProviderView{}
	}
	ctx.JSON(http.StatusOK, response)
}
