package handler

import (
	"context"
	"encoding/json"
	"main/argohandler"
	"main/db"
	"net/http"

	//	"github.com/gorilla/mux"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
)

type Cluster struct {
	ID              primitive.ObjectID `bson:"_id,omitempty"`
	Name            string             `json:"name"`
	Namespace       string             `json:"namespace"`
	ControlPlane    string             `json:"controlPlane"`
	PlatformVersion string             `json:"platformversion`
	Cpu             string             `json:"cpu"`
	Memory          string             `json:"memory"`
	CreatedAt       string             `json:"createdAt"`
	UserID          primitive.ObjectID `json:"userId"`
}

type Header struct {
	Authorization string `bson:"token"`
}

func CreateClusterHandler(w http.ResponseWriter, r *http.Request) {

	var cluster Cluster
	_ = json.NewDecoder(r.Body).Decode(&cluster)

	var header Header
	header.Authorization = r.Header.Get("Authorization")

	// vclusterCollection := db.Vclusters_details.FindOne(context.TODO(), bson.M{"name": Cluster.Name}).Decode(&existsCluster)

	if cluster.Name == "" || cluster.ControlPlane == "" || cluster.PlatformVersion == "" || cluster.Cpu == "" || cluster.Memory == "" {
		http.Error(w, "Invalid input", http.StatusBadRequest)
		return
	}

	var existsCluster Cluster
	_ = db.Vclusters_details.FindOne(context.TODO(), bson.M{"name": cluster.Name}).Decode(&existsCluster)

	if existsCluster.Name == cluster.Name {
		http.Error(w, "Cluster name is duplicated", http.StatusBadRequest)
		return
	}

	_, err := db.Vclusters_details.InsertOne(context.TODO(), cluster)
	if err != nil {
		http.Error(w, `{"message": "Could not create cluster"}`, http.StatusInternalServerError)
	}

	argohandler.CreateApp(cluster.Name, cluster.ControlPlane, cluster.PlatformVersion, cluster.Cpu, cluster.Memory, "userid")

	response := map[string]string{"message": "Cluster created"}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(response)

}

// func RegsiterClusterRoute(r *mux.Router) {
// 	r.HandleFunc("/createcluster", createClusterHandler).Methods("POST", "OPTIONS")
// }
