/*
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/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/validators"
)

func resourceK8sWgCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	log.Debugf("resourceK8sWgCreate: called with k8s id %d", d.Get("k8s_id").(int))

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

	if !haveK8sID {
		return diag.Errorf("resourceK8sWgCreate: can't create k8s cluster because K8sID %d is not allowed or does not exist", d.Get("k8s_id").(int))
	}

	c := m.(*controller.ControllerCfg)
	req := k8s.WorkersGroupAddRequest{
		K8SID:           uint64(d.Get("k8s_id").(int)),
		Name:            d.Get("name").(string),
		WorkerNum:       uint64(d.Get("num").(int)),
		WorkerCPU:       uint64(d.Get("cpu").(int)),
		WorkerRAM:       uint64(d.Get("ram").(int)),
		WorkerSEPID:     uint64(d.Get("worker_sep_id").(int)),
		WorkerSEPPool:   d.Get("worker_sep_pool").(string),
		Chipset:         d.Get("chipset").(string),
		StoragePolicyID: uint64(d.Get("storage_policy_id").(int)),
	}

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

	annotations, _ := d.Get("annotations").([]interface{})
	for _, annotation := range annotations {
		req.Annotations = append(req.Annotations, annotation.(string))
	}

	taints, _ := d.Get("taints").([]interface{})
	for _, taint := range taints {
		req.Taints = append(req.Taints, taint.(string))
	}

	if d.Get("disk") == nil {
		req.WorkerDisk = 0
	} else {
		req.WorkerDisk = uint64(d.Get("disk").(int))
	}

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

	resp, err := c.CloudAPI().K8S().WorkersGroupAdd(ctx, req)
	if err != nil {
		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("resourceK8sWgCreate: instance creating - %s", task.Stage)

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

			id, err := task.Result.ID()
			if err != nil {
				return diag.FromErr(err)
			}
			d.SetId(fmt.Sprint(d.Get("k8s_id").(int), "#", strconv.Itoa(id)))
			break
		}

		time.Sleep(time.Second * 20)
	}

	return resourceK8sWgRead(ctx, d, m)
}

func resourceK8sWgRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	log.Debugf("resourceK8sWgRead: called with %v", d.Id())

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

	workersComputeList := make([]compute.RecordCompute, 0)
	for _, info := range wg.DetailedInfo {
		compute, err := utilityComputeCheckPresence(ctx, d, m, info.ID)
		if err != nil {
			return diag.FromErr(err)
		}
		workersComputeList = append(workersComputeList, *compute)
	}

	d.Set("wg_id", wg.ID)
	if strings.Contains(d.Id(), "#") {
		k8sId, err := strconv.Atoi(strings.Split(d.Id(), "#")[0])
		if err != nil {
			return diag.FromErr(err)
		}

		d.Set("k8s_id", k8sId)
	} else {
		d.Set("k8s_id", d.Get("k8s_id"))
	}
	d.SetId(fmt.Sprintf("%d#%d", d.Get("k8s_id").(int), wg.ID))

	flattenWg(d, *wg, workersComputeList)

	return nil
}

func resourceK8sWgUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	log.Debugf("resourceK8sWgUpdate: called with k8s id %d", d.Get("k8s_id").(int))

	c := m.(*controller.ControllerCfg)

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

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

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

	if newNum := d.Get("num").(int); uint64(newNum) > wg.Num {
		req := k8s.WorkerAddRequest{
			K8SID:          uint64(d.Get("k8s_id").(int)),
			WorkersGroupID: wg.ID,
			Num:            uint64(newNum) - wg.Num,
			Chipset:        d.Get("chipset").(string),
		}

		_, err := c.CloudAPI().K8S().WorkerAdd(ctx, req)
		if err != nil {
			return diag.FromErr(err)
		}
	} else {
		for i := int(wg.Num) - 1; i >= newNum; i-- {
			req := k8s.DeleteWorkerFromGroupRequest{
				K8SID:          uint64(d.Get("k8s_id").(int)),
				WorkersGroupID: wg.ID,
				WorkerID:       wg.DetailedInfo[i].ID,
			}

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

	if d.HasChange("cloud_init") {
		req := k8s.UpdateWorkerNodesMetaDataRequest{
			K8SID:          uint64(d.Get("k8s_id").(int)),
			WorkersGroupID: wg.ID,
			UserData:       d.Get("cloud_init").(string),
		}

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

	return resourceK8sWgRead(ctx, d, m)
}

func resourceK8sWgDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	log.Debugf("resourceK8sWgDelete: called with k8s id %d", d.Get("k8s_id").(int))

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

	c := m.(*controller.ControllerCfg)
	req := k8s.WorkersGroupDeleteRequest{
		K8SID:          uint64(d.Get("k8s_id").(int)),
		WorkersGroupID: wg.ID,
	}

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

	d.SetId("")

	return nil
}

func resourceK8sWgSchemaMake() map[string]*schema.Schema {
	return map[string]*schema.Schema{
		"k8s_id": {
			Type:     schema.TypeInt,
			Required: true,
			//ForceNew:    true,
			Description: "ID of k8s instance.",
		},

		"name": {
			Type:     schema.TypeString,
			Required: true,
			//ForceNew:    true,
			Description: "Name of the worker group.",
		},

		"storage_policy_id": {
			Type:        schema.TypeInt,
			Required:    true,
			Description: "ID of the storage policy",
		},

		"num": {
			Type:        schema.TypeInt,
			Optional:    true,
			Default:     1,
			Description: "Number of worker nodes to create.",
		},

	"chipset": {
		Type:         schema.TypeString,
		Optional:     true,
		ValidateFunc: validation.StringInSlice([]string{"Q35", "i440fx"}, false),
		Default:      "Q35",
		Description:  "Type of the emulated system. Possible values: i440fx, Q35. Default: Q35",
	},

		"cpu": {
			Type:     schema.TypeInt,
			Optional: true,
			//ForceNew:    true,
			Default:     1,
			Description: "Worker node CPU count.",
		},

		"ram": {
			Type:     schema.TypeInt,
			Optional: true,
			//ForceNew:    true,
			Default: 1024,
			ValidateFunc: validation.All(
				validation.IntAtLeast(constants.MIN_RAM_PER_COMPUTE),
				validators.DivisibleBy(constants.RAM_DIVISIBILITY),
			),
			Description: "Worker node RAM in MB.",
		},

		"disk": {
			Type:        schema.TypeInt,
			Optional:    true,
			Computed:    true,
			Description: "Worker node boot disk size. If unspecified or 0, size is defined by OS image size.",
		},
		"labels": {
			Type:     schema.TypeList,
			Computed: true,
			Optional: true,
			Elem: &schema.Schema{
				Type: schema.TypeString,
			},
		},
		"annotations": {
			Type:     schema.TypeList,
			Computed: true,
			Optional: true,
			Elem: &schema.Schema{
				Type: schema.TypeString,
			},
		},
		"taints": {
			Type:     schema.TypeList,
			Computed: true,
			Optional: true,
			Elem: &schema.Schema{
				Type: schema.TypeString,
			},
		},
		"worker_sep_id": {
			Type:     schema.TypeInt,
			Optional: true,
		},
		"worker_sep_pool": {
			Type:     schema.TypeString,
			Optional: true,
		},
		"cloud_init": {
			Type:             schema.TypeString,
			Optional:         true,
			DiffSuppressFunc: cloudInitDiffSupperss,
		},
		"wg_id": {
			Type:        schema.TypeInt,
			Computed:    true,
			Description: "ID of k8s worker Group.",
		},
		"detailed_info": {
			Type:     schema.TypeList,
			Computed: true,
			Elem: &schema.Resource{
				Schema: detailedInfoSchemaMake(),
			},
		},
		"guid": {
			Type:     schema.TypeString,
			Computed: true,
		},
	}
}

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

		CreateContext: resourceK8sWgCreate,
		ReadContext:   resourceK8sWgRead,
		UpdateContext: resourceK8sWgUpdate,
		DeleteContext: resourceK8sWgDelete,

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

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

		Schema: resourceK8sWgSchemaMake(),
	}
}
