// Copyright © 2018 Banzai Cloud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package pke

import (
	"fmt"
	"net/http"

	"emperror.dev/errors"
	"github.com/gin-gonic/gin"

	"github.com/banzaicloud/pipeline/pkg/common"
)

// ListCommands Lists the commands for installing nodes in each nodePool
func (a *API) ListCommands(c *gin.Context) {
	cluster, ok := a.clusterGetter.GetClusterFromRequest(c)
	if !ok {
		err := errors.New("cluster not found")
		a.errorHandler.Handle(err)

		c.JSON(http.StatusNotFound, common.ErrorResponse{
			Code:    http.StatusNotFound,
			Message: "Cluster not found",
			Error:   err.Error(),
		})
		return
	}
	clusterCommander, ok := cluster.(interface {
		GetBootstrapCommand(nodePool, url, token string) (string, error)
		GetPipelineToken(tokenGenerator interface{}) (string, error)
	})
	if !ok {
		err := errors.New(fmt.Sprintf("not implemented for this type of cluster (%T)", cluster))
		a.errorHandler.Handle(err)

		c.JSON(http.StatusNotFound, common.ErrorResponse{
			Code:    http.StatusNotFound,
			Message: "Not implemented",
			Error:   err.Error(),
		})
		return
	}

	commands := map[string]string{}

	var nodePools []string

	if cl, ok := cluster.(interface {
		ListNodePools() ([]string, error)
	}); ok {
		np, err := cl.ListNodePools()
		if err != nil {
			err := errors.WrapIf(err, "can't list nodes")
			a.errorHandler.Handle(err)

			c.JSON(http.StatusInternalServerError, common.ErrorResponse{
				Code:    http.StatusInternalServerError,
				Message: "internal error",
				Error:   err.Error(),
			})
			return
		}

		nodePools = np
	}

	token, err := clusterCommander.GetPipelineToken(a.tokenGenerator)
	if err != nil {
		err := errors.WrapIf(err, "can't generate token")
		a.errorHandler.Handle(err)

		c.JSON(http.StatusInternalServerError, common.ErrorResponse{
			Code:    http.StatusInternalServerError,
			Message: "internal error",
			Error:   err.Error(),
		})
		return
	}

	for _, nodePool := range nodePools {
		commands[nodePool], _ = clusterCommander.GetBootstrapCommand(nodePool, a.externalBaseURL, token)
	}

	if len(commands) == 0 { // give some examples for the user...
		commands["master"], _ = clusterCommander.GetBootstrapCommand("master", a.externalBaseURL, token)
		commands["pool1"], _ = clusterCommander.GetBootstrapCommand("pool1", a.externalBaseURL, token)
	}

	c.JSON(http.StatusOK, commands)
}
