/*
Copyright (c) 2019-2023 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>
Tim Tkachev, <tvtkachev@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"
	log "github.com/sirupsen/logrus"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/compute"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/k8s"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/lb"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/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/dc"
	"repository.basistech.ru/BASIS/terraform-provider-decort/internal/status"
)

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

	c := m.(*controller.ControllerCfg)

	if diags := checkParamsExistence(ctx, d, c); diags != nil {
		return diags
	}

	createReq := k8s.CreateRequest{
		Name:            d.Get("name").(string),
		RGID:            uint64(d.Get("rg_id").(int)),
		K8CIID:          uint64(d.Get("k8sci_id").(int)),
		WorkerGroupName: "temp",
		NetworkPlugin:   d.Get("network_plugin").(string),
		StoragePolicyID: uint64(d.Get("storage_policy_id").(int)),
	}

	if num, ok := d.GetOk("num"); ok {
		createReq.MasterNum = uint64(num.(int))
	} else {
		createReq.MasterNum = 1
	}

	if cpu, ok := d.GetOk("cpu"); ok {
		createReq.MasterCPU = uint64(cpu.(int))
	} else {
		createReq.MasterCPU = 2
	}

	if ram, ok := d.GetOk("ram"); ok {
		createReq.MasterRAM = uint64(ram.(int))
	} else {
		createReq.MasterRAM = 2048
	}

	if disk, ok := d.GetOk("disk"); ok {
		createReq.MasterDisk = uint64(disk.(int))
	} else {
		createReq.MasterDisk = 0
	}

	if sepId, ok := d.GetOk("sep_id"); ok {
		createReq.MasterSEPID = uint64(sepId.(int))
	}

	if sepPool, ok := d.GetOk("sep_pool"); ok {
		createReq.MasterSEPPool = sepPool.(string)
	}

	if withLB, ok := d.GetOk("with_lb"); ok {
		createReq.WithLB = withLB.(bool)
	} else {
		createReq.WithLB = true
	}

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

	if zoneID, ok := d.GetOk("zone_id"); ok {
		createReq.ZoneID = uint64(zoneID.(int))
	}

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

	if haMode, ok := d.GetOk("ha_mode"); ok {
		createReq.HighlyAvailable = haMode.(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 initConfig, ok := d.GetOk("init_config"); ok {
		createReq.InitConfiguration = initConfig.(string)
	}

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

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

	if extNetOnly, ok := d.GetOk("extnet_only"); ok {
		createReq.ExtNetOnly = extNetOnly.(bool)
	}

	if desc, ok := d.GetOk("desc"); ok {
		createReq.Description = desc.(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
	}

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

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

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

		log.Debugf("resourceK8sControlPlaneCreate: 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)
	}

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

	delWGReq := k8s.WorkersGroupDeleteRequest{
		K8SID:          cluster.ID,
		WorkersGroupID: cluster.K8SGroups.Workers[0].ID,
	}

	_, err = c.CloudBroker().K8S().WorkersGroupDelete(ctx, delWGReq)
	if err != nil {
		return diag.FromErr(err)
	}

	return resourceK8sCPRead(ctx, d, m)
}

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

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

	switch k8sData.Status {
	case status.Modeled:
		return diag.Errorf("The k8s cluster is in status: %s, please, contact support for more information", k8sData.Status)
	case status.Destroying:
		return diag.Errorf("The k8s cluster is in progress with status: %s", k8sData.Status)
	case status.Destroyed:
		d.SetId("")
		return diag.Errorf("The resource cannot be updated because it has been destroyed")
	case status.Disabled:
		log.Debugf("The k8s cluster is in status: %s, troubles may occur with update. Please, enable compute first.", k8sData.Status)
	}
	c := m.(*controller.ControllerCfg)

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

	k8sList, err := utilityResourceK8sListCheckPresence(ctx, d, m)
	if err != nil {
		d.SetId("")
		return diag.FromErr(err)
	}

	curK8s := k8s.ItemK8S{}
	for _, k8sCluster := range k8sList.Data {
		if k8sCluster.ID == k8sData.ID {
			curK8s = k8sCluster
		}
	}
	if curK8s.ID == 0 {
		return diag.Errorf("Cluster with id %d not found", k8sData.ID)
	}

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

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

	var warnings dc.Warnings

	if _, ok := d.GetOk("k8s_id"); !ok {
		for _, worker := range k8sData.K8SGroups.Workers {
			err := fmt.Errorf("found worker-group with ID %d. Make sure to import it to decort_k8s_wg resource if you wish to manage it", worker.ID)
			warnings.Add(err)
		}
	}

	flattenResourceK8sCP(d, *k8sData, masterComputeList)

	lbGetReq := lb.GetRequest{
		LBID: k8sData.LBID,
	}

	if d.Get("with_lb").(bool) || k8sData.LBID != 0 {
		lb, err := c.CloudBroker().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: k8sData.ID,
	}

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

	d.Set("kubeconfig", kubeconfig)

	return warnings.Get()
}

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

	c := m.(*controller.ControllerCfg)

	if diags := checkParamsExistence(ctx, d, c); diags != nil {
		return diags
	}

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

	hasChanged := false

	switch k8sData.Status {
	case status.Modeled:
		return diag.Errorf("The k8s cluster is in status: %s, please, contact support for more information", k8sData.Status)
	case status.Deleted:
		err := handleRestore(ctx, d, c, k8sData)
		if err != nil {
			return diag.FromErr(err)
		}
		hasChanged = true
	case status.Destroying:
		return diag.Errorf("The k8s cluster is in progress with status: %s", k8sData.Status)
	case status.Destroyed:
		d.SetId("")
		return diag.Errorf("The resource cannot be updated because it has been destroyed")
	case status.Disabled:
		log.Debugf("The k8s cluster is in status: %s, troubles may occur with update. Please, enable compute first.", k8sData.Status)
	}

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

	if d.HasChanges("name", "desc") {
		err := handleUpdate(ctx, d, c, k8sData)
		if err != nil {
			return diag.FromErr(err)
		}
	}

	if d.HasChange("enabled") {
		err := handleEnable(ctx, c, d.Get("enabled").(bool), k8sData.ID)
		if err != nil {
			return diag.FromErr(err)
		}
	}

	if d.HasChange("zone_id") {
		start := d.Get("start").(bool)
		err := handleZoneID(ctx, c, k8sData.ID, uint64(d.Get("zone_id").(int)), start)
		if err != nil {
			return diag.FromErr(err)
		}
	}

	if d.HasChange("start") {
		err := handleStart(ctx, c, d.Get("start").(bool), k8sData)
		if err != nil {
			return diag.FromErr(err)
		}
	}

	if d.HasChange("num") {
		err := handleUpdateNum(ctx, d, c, k8sData)
		if err != nil {
			return diag.FromErr(err)
		}
	}

	if d.HasChange("lb_sysctl_params") && d.Get("with_lb").(bool) {
		err := handleUpdateLbSysctlParams(ctx, d, c, k8sData)
		if err != nil {
			return diag.FromErr(err)
		}
	}

	return nil
}

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

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

	c := m.(*controller.ControllerCfg)
	req := k8s.DeleteRequest{
		K8SID: k8sData.ID,
	}

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

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

	d.SetId("")

	return nil
}

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

		CreateContext: resourceK8sCPCreate,
		ReadContext:   resourceK8sCPRead,
		UpdateContext: resourceK8sCPUpdate,
		DeleteContext: resourceK8sCPDelete,

		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: resourceK8sCPSchemaMake(),
	}
}

func handleUpdateNum(ctx context.Context, d *schema.ResourceData, c *controller.ControllerCfg, k8sData *k8s.RecordK8S) error {

	oldVal, newVal := d.GetChange("num")

	if oldVal.(int) > newVal.(int) {
		ids := make([]uint64, 0)
		for i := oldVal.(int) - 1; i >= newVal.(int); i-- {
			id := k8sData.K8SGroups.Masters.DetailedInfo[i].ID
			ids = append(ids, id)
		}

		req := k8s.DeleteMasterFromGroupRequest{
			K8SID:         k8sData.ID,
			MasterGroupID: k8sData.K8SGroups.Masters.ID,
			MasterIDs:     ids,
		}

		_, err := c.CloudBroker().K8S().DeleteMasterFromGroup(ctx, req)
		if err != nil {
			return err
		}
	}

	return nil
}

func handleUpdate(ctx context.Context, d *schema.ResourceData, c *controller.ControllerCfg, k8sData *k8s.RecordK8S) error {
	updateReq := k8s.UpdateRequest{K8SID: k8sData.ID}

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

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

	_, err := c.CloudBroker().K8S().Update(ctx, updateReq)
	if err != nil {
		return err
	}

	return nil
}

func handleRestore(ctx context.Context, d *schema.ResourceData, c *controller.ControllerCfg, k8sData *k8s.RecordK8S) error {

	if restore, ok := d.GetOk("restore"); ok && restore.(bool) {
		restoreReq := k8s.RestoreRequest{
			K8SID: k8sData.ID,
		}

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

		err = handleEnable(ctx, c, d.Get("enabled").(bool), k8sData.ID)
		if err != nil {
			return err
		}

		err = handleStart(ctx, c, d.Get("start").(bool), k8sData)
		if err != nil {
			return err
		}
	}

	return nil
}

func handleEnable(ctx context.Context, c *controller.ControllerCfg, enable bool, k8sId uint64) error {
	if enable {
		enableReq := k8s.EnableRequest{K8SID: k8sId}

		_, err := c.CloudBroker().K8S().Enable(ctx, enableReq)
		if err != nil {
			return err
		}

	} else {
		disableReq := k8s.DisableRequest{K8SID: k8sId}

		_, err := c.CloudBroker().K8S().Disable(ctx, disableReq)
		if err != nil {
			return err
		}
	}
	return nil
}

func handleStart(ctx context.Context, c *controller.ControllerCfg, start bool, k8sData *k8s.RecordK8S) error {
	if start {
		if k8sData.TechStatus == "STOPPED" {
			startReq := k8s.StartRequest{K8SID: k8sData.ID}

			_, err := c.CloudBroker().K8S().Start(ctx, startReq)
			if err != nil {
				return err
			}
		}
	} else {
		if k8sData.TechStatus == "STARTED" {
			stopReq := k8s.StopRequest{K8SID: k8sData.ID}

			_, err := c.CloudBroker().K8S().Stop(ctx, stopReq)
			if err != nil {
				return err
			}
		}
	}
	return nil
}

func handleZoneID(ctx context.Context, c *controller.ControllerCfg, k8sId uint64, zoneID uint64, start bool) error {

	if start {
		stopReq := k8s.StopRequest{
			K8SID: k8sId,
		}

		_, err := c.CloudBroker().K8S().Stop(ctx, stopReq)
		if err != nil {
			return err
		}
	}

	req := k8s.MigrateToZoneRequest{
		K8SID:  k8sId,
		ZoneID: zoneID,
	}

	_, err := c.CloudBroker().K8S().MigrateToZone(ctx, req)
	if err != nil {
		return err
	}

	if start {
		startReq := k8s.StartRequest{
			K8SID: k8sId,
		}

		_, err := c.CloudBroker().K8S().Start(ctx, startReq)
		if err != nil {
			return err
		}
	}

	return nil
}

func handleUpdateLbSysctlParams(ctx context.Context, d *schema.ResourceData, c *controller.ControllerCfg, k8sData *k8s.RecordK8S) error {

	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:         k8sData.LBID,
			SysctlParams: res,
		}

		_, err := c.CloudBroker().LB().UpdateSysctlParams(ctx, req)
		return err
	}
	return nil
}
