/*
Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved.
Authors:
Petr Krutov, <petr.krutov@digitalenergy.online>
Stanislav Solovev, <spsolovev@digitalenergy.online>
Kasim Baybikov, <kmbaybikov@basistech.ru>

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.
*/

/*
Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud
Orchestration Technology) with Terraform by Hashicorp.

Source code: https://repository.basistech.ru/BASIS/terraform-provider-decort

Please see README.md to learn where to place source code so that it
builds seamlessly.

Documentation: https://repository.basistech.ru/BASIS/terraform-provider-decort/wiki
*/

package k8s

import (
	"context"
	"fmt"
	"strconv"
	"strings"
	"time"

	"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
	log "github.com/sirupsen/logrus"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/compute"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/k8s"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/lb"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/tasks"
	"repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants"
	"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
	"repository.basistech.ru/BASIS/terraform-provider-decort/internal/status"
)

func resourceK8sCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	log.Debugf("resourceK8sCreate: called with name %s, rg %d", d.Get("name").(string), d.Get("rg_id").(int))

	haveRGID, err := existRGID(ctx, d, m)
	if err != nil {
		return diag.FromErr(err)
	}

	if !haveRGID {
		return diag.Errorf("resourceK8sCreate: can't create k8s cluster because RGID %d is not allowed or does not exist", d.Get("rg_id").(int))
	}

	haveK8sciID, err := existK8sCIID(ctx, d, m)
	if err != nil {
		return diag.FromErr(err)
	}

	if !haveK8sciID {
		return diag.Errorf("resourceK8sCreate: can't create k8s cluster because K8sCIID %d is not allowed or does not exist", d.Get("k8sci_id").(int))
	}

	if _, ok := d.GetOk("extnet_id"); ok {
		haveExtNetID, err := existExtNetID(ctx, d, m)
		if err != nil {
			return diag.FromErr(err)
		}

		if !haveExtNetID {
			return diag.Errorf("resourceK8sCreate: can't create k8s cluster because ExtNetID %d is not allowed or does not exist", d.Get("extnet_id").(int))
		}
	}

	c := m.(*controller.ControllerCfg)
	createReq := k8s.CreateRequest{}

	createReq.Name = d.Get("name").(string)
	createReq.RGID = uint64(d.Get("rg_id").(int))
	createReq.K8SCIID = uint64(d.Get("k8sci_id").(int))
	createReq.WorkerGroupName = d.Get("wg_name").(string)
	createReq.NetworkPlugin = d.Get("network_plugin").(string)

	var masterNode K8sNodeRecord
	if masters, ok := d.GetOk("masters"); ok {
		masterNode = parseDefaultNode(masters.([]interface{}))
	} else {
		masterNode = nodeMasterDefault()
	}
	createReq.MasterNum = uint(masterNode.Num)
	createReq.MasterCPU = uint(masterNode.Cpu)
	createReq.MasterRAM = uint64(masterNode.Ram)
	createReq.MasterDisk = uint(masterNode.Disk)
	createReq.MasterSEPID = uint64(masterNode.SepID)
	createReq.MasterSEPPool = masterNode.SepPool

	var workerNode K8sNodeRecord
	if workers, ok := d.GetOk("workers"); ok {
		workerNode = parseDefaultNode(workers.([]interface{}))
	} else {
		workerNode = nodeWorkerDefault()
	}

	createReq.WorkerNum = uint(workerNode.Num)
	createReq.WorkerCPU = uint(workerNode.Cpu)
	createReq.WorkerRAM = uint64(workerNode.Ram)
	createReq.WorkerDisk = uint(workerNode.Disk)
	createReq.WorkerSEPID = uint64(workerNode.SepID)
	createReq.WorkerSEPPool = workerNode.SepPool

	if labels, ok := d.GetOk("labels"); ok {
		labels := labels.([]interface{})
		for _, label := range labels {
			if !strings.HasPrefix(label.(string), "workersGroupName") {
				createReq.Labels = append(createReq.Labels, label.(string))
			}
		}
	}

	if taints, ok := d.GetOk("taints"); ok {
		taints := taints.([]interface{})
		for _, taint := range taints {
			createReq.Taints = append(createReq.Taints, taint.(string))
		}
	}

	if annotations, ok := d.GetOk("annotations"); ok {
		annotations := annotations.([]interface{})
		for _, annotation := range annotations {
			createReq.Annotations = append(createReq.Annotations, annotation.(string))
		}
	}

	createReq.WithLB = d.Get("with_lb").(bool)

	///4.4.0
	createReq.HighlyAvailable = d.Get("ha_mode").(bool)

	if additionalSans, ok := d.GetOk("additional_sans"); ok {
		addSans := additionalSans.([]interface{})
		resSans := make([]string, 0)
		for _, san := range addSans {
			resSans = append(resSans, san.(string))
		}

		createReq.AdditionalSANs = resSans
	}

	if clusterConfig, ok := d.GetOk("cluster_config"); ok {
		createReq.ClusterConfiguration = clusterConfig.(string)
	}

	if kubeletConfig, ok := d.GetOk("kubelet_config"); ok {
		createReq.KubeletConfiguration = kubeletConfig.(string)
	}

	if kubeProxyConfig, ok := d.GetOk("kube_proxy_config"); ok {
		createReq.KubeProxyConfiguration = kubeProxyConfig.(string)
	}

	if joinConfig, ok := d.GetOk("join_config"); ok {
		createReq.JoinConfiguration = joinConfig.(string)
	}

	if cloudInit, ok := d.GetOk("cloud_init"); ok {
		createReq.UserData = cloudInit.(string)
	}

	if initConfig, ok := d.GetOk("init_config"); ok {
		createReq.InitConfiguration = initConfig.(string)
	}

	if lbSysctlParams, ok := d.GetOk("lb_sysctl_params"); ok {
		syscrlSliceMaps := lbSysctlParams.([]interface{})
		res := make([]map[string]interface{}, 0, len(syscrlSliceMaps))
		for _, syscrlMap := range syscrlSliceMaps {
			tempMap := make(map[string]interface{})
			for k, v := range syscrlMap.(map[string]interface{}) {
				if intVal, err := strconv.Atoi(v.(string)); err == nil {
					tempMap[k] = intVal
					continue
				}
				tempMap[k] = v.(string)
			}
			res = append(res, tempMap)
		}
		createReq.LbSysctlParams = res
	}

	if oidcCertificate, ok := d.GetOk("oidc_cert"); ok {
		createReq.OidcCertificate = oidcCertificate.(string)
	}

	///

	if chipset, ok := d.GetOk("chipset"); ok {
		createReq.Chipset = chipset.(string)
	}

	createReq.ExtNetOnly = d.Get("extnet_only").(bool)

	if extNet, ok := d.GetOk("extnet_id"); ok {
		createReq.ExtNetID = uint64(extNet.(int))
	} else {
		createReq.ExtNetID = 0
	}

	if vins, ok := d.GetOk("vins_id"); ok {
		createReq.VinsId = uint64(vins.(int))
	} else {
		createReq.VinsId = 0
	}

	if desc, ok := d.GetOk("desc"); ok {
		createReq.Description = desc.(string)
	}

	resp, err := c.CloudAPI().K8S().Create(ctx, createReq)
	if err != nil {
		d.SetId("")
		return diag.FromErr(err)
	}

	taskReq := tasks.GetRequest{
		AuditID: strings.Trim(resp, `"`),
	}

	for {
		task, err := c.CloudAPI().Tasks().Get(ctx, taskReq)
		if err != nil {
			return diag.FromErr(err)
		}

		log.Debugf("resourceK8sCreate: instance creating - %s", task.Stage)

		if task.Completed {
			if task.Error != "" {
				return diag.FromErr(fmt.Errorf("cannot create k8s instance: %v", task.Error))
			}

			id, err := task.Result.ID()
			if err != nil {
				return diag.FromErr(err)
			}
			d.SetId(strconv.Itoa(id))
			break
		}

		time.Sleep(time.Second * 20)
	}

	return resourceK8sRead(ctx, d, m)
}

func resourceK8sRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	cluster, err := utilityK8sCheckPresence(ctx, d, m)
	if err != nil {
		d.SetId("")
		return diag.FromErr(err)
	}

	c := m.(*controller.ControllerCfg)

	hasChanged := false

	switch cluster.Status {
	case status.Modeled:
		return diag.Errorf("The k8s cluster is in status: %s, please, contact support for more information", cluster.Status)
	case status.Creating:
	case status.Created:
	case status.Deleting:
	case status.Deleted:
		// id, _ := strconv.ParseUint(d.Id(), 10, 64)
		// restoreReq := k8s.RestoreRequest{
		// 	K8SID: id,
		// }

		// _, err := c.CloudAPI().K8S().Restore(ctx, restoreReq)
		// if err != nil {
		// 	return diag.FromErr(err)
		// }

		// enableReq := k8s.DisableEnableRequest{
		// 	K8SID: id,
		// }

		// _, err = c.CloudAPI().K8S().Enable(ctx, enableReq)
		// if err != nil {
		// 	return diag.FromErr(err)
		// }

		// hasChanged = true
	case status.Destroying:
		return diag.Errorf("The k8s cluster is in progress with status: %s", cluster.Status)
	case status.Destroyed:
		d.SetId("")
		return diag.Errorf("The resource cannot be updated because it has been destroyed")
		// return resourceK8sCreate(ctx, d, m)
	case status.Enabling:
	case status.Enabled:
	case status.Disabling:
	case status.Disabled:
		log.Debugf("The k8s cluster is in status: %s, troubles may occur with update. Please, enable compute first.", cluster.Status)
	case status.Restoring:
	}

	if hasChanged {
		cluster, err = utilityK8sCheckPresence(ctx, d, m)
		if cluster == nil {
			d.SetId("")
			if err != nil {
				return diag.FromErr(err)
			}
			return nil
		}
	}

	if d.Get("start").(bool) {
		if cluster.TechStatus == "STOPPED" {
			req := k8s.StartRequest{
				K8SID: cluster.ID,
			}
			_, err := c.CloudAPI().K8S().Start(ctx, req)
			if err != nil {
				return diag.FromErr(err)
			}
		}
	}

	k8sList, err := utilityK8sListForResourceCheckPresence(ctx, d, m)
	if err != nil {
		d.SetId("")
		return diag.FromErr(err)
	}
	curK8s := k8s.ItemK8SCluster{}
	for _, k8sCluster := range k8sList.Data {
		if k8sCluster.ID == cluster.ID {
			curK8s = k8sCluster
		}
	}
	if curK8s.ID == 0 {
		return diag.Errorf("Cluster with id %d not found", cluster.ID)
	}

	d.Set("vins_id", curK8s.VINSID)

	masterComputeList := make([]compute.RecordCompute, 0, len(cluster.K8SGroups.Masters.DetailedInfo))
	workersComputeList := make([]compute.RecordCompute, 0, len(cluster.K8SGroups.Workers))
	for _, masterNode := range cluster.K8SGroups.Masters.DetailedInfo {
		compute, err := utilityComputeCheckPresence(ctx, d, m, masterNode.ID)
		if err != nil {
			return diag.FromErr(err)
		}
		masterComputeList = append(masterComputeList, *compute)
	}
	for _, worker := range cluster.K8SGroups.Workers {
		for _, info := range worker.DetailedInfo {
			compute, err := utilityComputeCheckPresence(ctx, d, m, info.ID)
			if err != nil {
				return diag.FromErr(err)
			}
			workersComputeList = append(workersComputeList, *compute)
		}
	}

	flattenResourceK8s(d, *cluster, masterComputeList, workersComputeList)

	if d.Get("with_lb").(bool) || cluster.LBID != 0 {
		lbGetReq := lb.GetRequest{
			LBID: cluster.LBID,
		}

		lb, err := c.CloudAPI().LB().Get(ctx, lbGetReq)
		if err != nil {
			return diag.FromErr(err)
		}

		d.Set("extnet_id", lb.ExtNetID)
		d.Set("lb_ip", lb.PrimaryNode.FrontendIP)
	}

	kubeconfigReq := k8s.GetConfigRequest{
		K8SID: cluster.ID,
	}

	kubeconfig, err := c.CloudAPI().K8S().GetConfig(ctx, kubeconfigReq)
	if err != nil {
		log.Warnf("could not get kubeconfig: %v", err)
	}

	d.Set("kubeconfig", kubeconfig)

	return nil
}

func resourceK8sUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	log.Debugf("resourceK8sUpdate: called with id %s, rg %d", d.Id(), d.Get("rg_id").(int))

	c := m.(*controller.ControllerCfg)

	haveRGID, err := existRGID(ctx, d, m)
	if err != nil {
		return diag.FromErr(err)
	}

	if !haveRGID {
		return diag.Errorf("resourceK8sUpdate: can't update k8s cluster because RGID %d is not allowed or does not exist", d.Get("rg_id").(int))
	}

	haveK8sciID, err := existK8sCIID(ctx, d, m)
	if err != nil {
		return diag.FromErr(err)
	}

	if !haveK8sciID {
		return diag.Errorf("resourceK8sUpdate: can't update k8s cluster because K8sCIID %d is not allowed or does not exist", d.Get("k8sci_id").(int))
	}

	cluster, err := utilityK8sCheckPresence(ctx, d, m)
	if err != nil {
		return diag.FromErr(err)
	}

	hasChanged := false

	switch cluster.Status {
	case status.Modeled:
		return diag.Errorf("The k8s cluster is in status: %s, please, contact support for more information", cluster.Status)
	case status.Creating:
	case status.Created:
	case status.Deleting:
	case status.Deleted:
		id, _ := strconv.ParseUint(d.Id(), 10, 64)
		restoreReq := k8s.RestoreRequest{
			K8SID: id,
		}

		_, err := c.CloudAPI().K8S().Restore(ctx, restoreReq)
		if err != nil {
			return diag.FromErr(err)
		}

		enableReq := k8s.DisableEnableRequest{
			K8SID: id,
		}

		_, err = c.CloudAPI().K8S().Enable(ctx, enableReq)
		if err != nil {
			return diag.FromErr(err)
		}

		hasChanged = true
	case status.Destroying:
		return diag.Errorf("The k8s cluster is in progress with status: %s", cluster.Status)
	case status.Destroyed:
		d.SetId("")
		return diag.Errorf("The resource cannot be updated because it has been destroyed")
		// return resourceK8sCreate(ctx, d, m)
	case status.Enabling:
	case status.Enabled:
	case status.Disabling:
	case status.Disabled:
		log.Debugf("The k8s cluster is in status: %s, troubles may occur with update. Please, enable compute first.", cluster.Status)
	case status.Restoring:
	}

	if hasChanged {
		cluster, err = utilityK8sCheckPresence(ctx, d, m)
		if cluster == nil {
			d.SetId("")
			if err != nil {
				return diag.FromErr(err)
			}
			return nil
		}
	}

	updateReq := k8s.UpdateRequest{K8SID: cluster.ID}
	doBasicUpdate := false

	if d.HasChange("name") {
		updateReq.Name = d.Get("name").(string)
		doBasicUpdate = true
	}

	if d.HasChange("desc") {
		updateReq.Description = d.Get("desc").(string)
		doBasicUpdate = true
	}

	if doBasicUpdate {
		_, err := c.CloudAPI().K8S().Update(ctx, updateReq)
		if err != nil {
			return diag.FromErr(err)
		}
	}

	if d.HasChange("workers") {
		err := handleWorkersChange(ctx, d, c, cluster)
		if err != nil {
			return diag.FromErr(err)
		}
	}

	if d.HasChange("start") {
		if d.Get("start").(bool) {
			if cluster.TechStatus == "STOPPED" {
				req := k8s.StartRequest{
					K8SID: cluster.ID,
				}
				_, err := c.CloudAPI().K8S().Start(ctx, req)
				if err != nil {
					return diag.FromErr(err)
				}
			}
		} else {
			if cluster.TechStatus == "STARTED" {
				req := k8s.StopRequest{
					K8SID: cluster.ID,
				}
				_, err := c.CloudAPI().K8S().Stop(ctx, req)
				if err != nil {
					return diag.FromErr(err)
				}
			}
		}
	}

	if d.HasChange("lb_sysctl_params") && d.Get("with_lb").(bool) {
		lbSysctlParams := d.Get("lb_sysctl_params").([]interface{})
		res := make([]map[string]interface{}, 0, len(lbSysctlParams))
		for _, syscrlMap := range lbSysctlParams {
			tempMap := make(map[string]interface{})
			for k, v := range syscrlMap.(map[string]interface{}) {
				if intVal, err := strconv.Atoi(v.(string)); err == nil {
					tempMap[k] = intVal
					continue
				}
				tempMap[k] = v.(string)
			}
			res = append(res, tempMap)
		}
		if len(res) > 0 {
			req := lb.UpdateSysctParamsRequest{
				LBID:         cluster.LBID,
				SysctlParams: res,
			}
			_, err := c.CloudAPI().LB().UpdateSysctlParams(ctx, req)
			if err != nil {
				return diag.FromErr(err)
			}
		}
	}

	return resourceK8sRead(ctx, d, m)
}

func resourceK8sDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {

	log.Debugf("resourceK8sDelete: called with id %s, rg %d", d.Id(), d.Get("rg_id").(int))

	cluster, err := utilityK8sCheckPresence(ctx, d, m)
	if err != nil {
		return diag.FromErr(err)
	}

	req := k8s.DeleteRequest{K8SID: cluster.ID}

	if val, ok := d.GetOk("permanently"); ok {
		req.Permanently = val.(bool)
	}

	c := m.(*controller.ControllerCfg)

	_, err = c.CloudAPI().K8S().Delete(ctx, req)
	if err != nil {
		return diag.FromErr(err)
	}

	return nil
}

func resourceK8sSchemaMake() map[string]*schema.Schema {
	return map[string]*schema.Schema{
		"name": {
			Type:        schema.TypeString,
			Required:    true,
			Description: "Name of the cluster.",
		},
		"rg_id": {
			Type:     schema.TypeInt,
			Required: true,
			//ForceNew:    true,
			Description: "Resource group ID that this instance belongs to.",
		},
		"k8sci_id": {
			Type:     schema.TypeInt,
			Required: true,
			//ForceNew:    true,
			Description: "ID of the k8s catalog item to base this instance on.",
		},
		"wg_name": {
			Type:        schema.TypeString,
			Required:    true,
			Description: "Name for first worker group created with cluster.",
		},
		"network_plugin": {
			Type:         schema.TypeString,
			Required:     true,
			Description:  "Network plugin to be used",
			ValidateFunc: validation.StringInSlice([]string{"flannel", "weavenet", "calico"}, true),
		},
		"labels": {
			Type:     schema.TypeList,
			Optional: true,
			Elem: &schema.Schema{
				Type: schema.TypeString,
			},
		},
		"taints": {
			Type:     schema.TypeList,
			Optional: true,
			Elem: &schema.Schema{
				Type: schema.TypeString,
			},
		},
		"annotations": {
			Type:     schema.TypeList,
			Optional: true,
			Elem: &schema.Schema{
				Type: schema.TypeString,
			},
		},
		"masters": {
			Type:     schema.TypeList,
			Optional: true,
			Computed: true,
			//ForceNew: true,
			MaxItems: 1,
			Elem: &schema.Resource{
				Schema: mastersSchemaMake(),
			},
			Description: "Master node(s) configuration.",
		},
		"workers": {
			Type:     schema.TypeList,
			Optional: true,
			Computed: true,
			Elem: &schema.Resource{
				Schema: workersSchemaMake(),
			},
			Description: "Worker node(s) configuration.",
		},
		"with_lb": {
			Type:        schema.TypeBool,
			Optional:    true,
			Default:     true,
			Description: "Create k8s with load balancer if true.",
		},
		"extnet_only": {
			Type:        schema.TypeBool,
			Optional:    true,
			Default:     false,
			Description: "Use only selected ExtNet for infrastructure connections",
		},
		"extnet_id": {
			Type:     schema.TypeInt,
			Optional: true,
			Computed: true,
			//ForceNew:    true,
			Description: "ID of the external network to connect workers to. If omitted network will be chosen by the platfom.",
		},
		"permanently": {
			Type:        schema.TypeBool,
			Optional:    true,
			Default:     false,
			Description: "Determines if cluster should be destroyed",
		},

		///4.4.0
		"cloud_init": {
			Type:        schema.TypeString,
			Optional:    true,
			Description: "Meta data for working group computes, format YAML 'user_data': 1111",
		},
		"join_config": {
			Type:        schema.TypeString,
			Optional:    true,
			Description: "is used to configure the behavior and settings for joining a node to a cluster. It includes parameters such as the cluster's control plane endpoint, token, and certificate key. insert a valid JSON string with all levels of nesting.",
		},
		"kube_proxy_config": {
			Type:        schema.TypeString,
			Optional:    true,
			Description: "is used to configure the behavior and settings of the Kube-proxy, which is responsible for network proxying and load balancing within the cluster. It includes parameters such as proxy mode, cluster IP ranges, and other Kube-proxy specific configurations. insert a valid JSON string with all levels of nesting.",
		},
		"kubelet_config": {
			Type:        schema.TypeString,
			Optional:    true,
			Description: "is used to configure the behavior and settings of the Kubelet, which is the primary node agent that runs on each node in the cluster. It includes parameters such as node IP address, resource allocation, pod eviction policies, and other Kubelet-specific configurations. insert a valid JSON string with all levels of nesting.",
		},
		"cluster_config": {
			Type:        schema.TypeString,
			Optional:    true,
			Description: "is used to define global settings and configurations for the entire cluster. It includes parameters such as cluster name, DNS settings, authentication methods, and other cluster-wide configurations. insert a valid JSON string with all levels of nesting.",
		},
		"init_config": {
			Type:        schema.TypeString,
			Optional:    true,
			Description: "is used to define settings and actions that should be performed before any other component in the cluster starts. It allows you to configure things like node registration, network setup, and other initialization tasks. insert a valid JSON string with all levels of nesting.",
		},
		"additional_sans": {
			Type:        schema.TypeList,
			Optional:    true,
			Description: "Optional extra Subject Alternative Names (SANs) to use for the API Server serving certificate. Can be both IP addresses and DNS names",
			Elem: &schema.Schema{
				Type: schema.TypeString,
			},
		},
		"ha_mode": {
			Type:        schema.TypeBool,
			Optional:    true,
			Description: "Use Highly Available schema for LB deploy",
		},
		"lb_sysctl_params": {
			Type:        schema.TypeList,
			Optional:    true,
			Description: "Custom sysctl values for Load Balancer instance. Applied on boot.",
			Elem: &schema.Schema{
				Type: schema.TypeMap,
				Elem: &schema.Schema{
					Type: schema.TypeString,
				},
			},
		},
		"oidc_cert": {
			Type:        schema.TypeString,
			Optional:    true,
			Description: "insert ssl certificate in x509 pem format",
		},

		"chipset": {
			Type:        schema.TypeString,
			Optional:    true,
			Description: "Type of the emulated system.",
		},

		"desc": {
			Type:        schema.TypeString,
			Optional:    true,
			Description: "Text description of this instance.",
		},
		"start": {
			Type:        schema.TypeBool,
			Optional:    true,
			Default:     true,
			Description: "Start k8s cluster",
		},

		"acl": {
			Type:     schema.TypeList,
			Computed: true,
			Elem: &schema.Resource{
				Schema: aclGroupSchemaMake(),
			},
		},
		"account_id": {
			Type:     schema.TypeInt,
			Computed: true,
		},
		"account_name": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"bservice_id": {
			Type:     schema.TypeInt,
			Computed: true,
		},
		"created_by": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"created_time": {
			Type:     schema.TypeInt,
			Computed: true,
		},
		"deleted_by": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"deleted_time": {
			Type:     schema.TypeInt,
			Computed: true,
		},
		"k8s_ci_name": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"lb_id": {
			Type:     schema.TypeInt,
			Computed: true,
		},
		"lb_ip": {
			Type:        schema.TypeString,
			Computed:    true,
			Description: "IP address of default load balancer.",
		},
		"rg_name": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"status": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"tech_status": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"updated_by": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"updated_time": {
			Type:     schema.TypeInt,
			Computed: true,
		},
		"default_wg_id": {
			Type:        schema.TypeInt,
			Computed:    true,
			Description: "ID of default workers group for this instace.",
		},
		"kubeconfig": {
			Type:        schema.TypeString,
			Computed:    true,
			Description: "Kubeconfig for cluster access.",
		},
		"vins_id": {
			Type:        schema.TypeInt,
			Optional:    true,
			Computed:    true,
			Description: "ID of default vins for this instace.",
		},
	}
}

func ResourceK8s() *schema.Resource {
	return &schema.Resource{
		SchemaVersion: 1,

		CreateContext: resourceK8sCreate,
		ReadContext:   resourceK8sRead,
		UpdateContext: resourceK8sUpdate,
		DeleteContext: resourceK8sDelete,

		Importer: &schema.ResourceImporter{
			StateContext: schema.ImportStatePassthroughContext,
		},

		Timeouts: &schema.ResourceTimeout{
			Create:  &constants.Timeout30m,
			Read:    &constants.Timeout600s,
			Update:  &constants.Timeout600s,
			Delete:  &constants.Timeout600s,
			Default: &constants.Timeout600s,
		},

		Schema: resourceK8sSchemaMake(),
	}
}
