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

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 disks

import (
	"context"
	"errors"
	"fmt"
	"strconv"

	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/disks"
	"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"

	"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
	log "github.com/sirupsen/logrus"
)

func resourceDiskCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	log.Debugf("resourceDiskCreate: called for disk %s", d.Get("disk_name").(string))
	c := m.(*controller.ControllerCfg)

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

	req := disks.CreateRequest{
		AccountID:       uint64(d.Get("account_id").(int)),
		StoragePolicyID: uint64(d.Get("storage_policy_id").(int)),
		Name:            d.Get("disk_name").(string),
		Size:            uint64(d.Get("size_max").(int)),
	}

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

	if sepID, ok := d.GetOk("sep_id"); ok {
		req.SEPID = uint64(sepID.(int))
	}

	if pool, ok := d.GetOk("pool"); ok {
		req.Pool = pool.(string)
	}

	if cache, ok := d.GetOk("cache"); ok {
		req.Cache = cache.(string)
	}

	if blkDiscard, ok := d.GetOk("blk_discard"); ok {
		req.BLKDiscard = blkDiscard.(bool)
	}

	diskID, err := c.CloudBroker().Disks().Create(ctx, req)
	if err != nil {
		d.SetId("")
		return diag.FromErr(err)
	}

	d.SetId(strconv.FormatUint(diskID, 10))
	d.Set("disk_id", diskID)

	w := dc.Warnings{}

	if _, ok := d.GetOk("node_ids"); ok {
		log.Debugf("resourceDiskCreate: present for disk %d", d.Get("disk_id"))
		if err := resourceDiskChangeNodes(ctx, d, m, true); err != nil {
			w.Add(err)
		}
		log.Debugf("resourceDiskCreate: finished present for disk %d", d.Get("disk_id"))
	}

	if _, ok := d.GetOk("block_size"); ok {
		if err := resourceDiskChangeBlockSize(ctx, d, m); err != nil {
			w.Add(err)
		}
	}

	if _, ok := d.GetOk("iotune"); ok {
		if err := resourceDiskChangeIotune(ctx, d, m); err != nil {
			w.Add(err)
		}
	}

	if shareable := d.Get("shareable"); shareable.(bool) {
		if err := resourceDiskChangeShareable(ctx, d, m); err != nil {
			w.Add(err)
		}
	}

	return append(w.Get(), resourceDiskRead(ctx, d, m)...)
}

func resourceDiskRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	log.Debugf("resourceDiskRead: called for disk_id %d", d.Get("disk_id").(int))
	w := dc.Warnings{}

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

	hasChangeState := false

	switch disk.Status {
	case status.Destroyed, status.Purged:
		d.Set("disk_id", 0)
		d.SetId("")
		return diag.Errorf("The resource cannot be read because it has been destroyed")
		//return resourceDiskCreate(ctx, d, m)
	case status.Deleted:
		//hasChangeState = true
		//if err := resourceDiskRestore(ctx, d, m); err != nil {
		//	w.Add(err)
		//}
	case status.Assigned:
	case status.Modeled:
		return diag.Errorf("The disk is in status: %s, please, contact support for more information", disk.Status)
	case status.Creating:
	case status.Created:
	case status.Allocated:
	case status.Unallocated:
	}

	if hasChangeState {
		disk, err = utilityDiskCheckPresence(ctx, d, m)
		if err != nil {
			d.SetId("")
			return diag.FromErr(err)
		}
	}

	flattenDisk(d, disk)

	return w.Get()
}

func resourceDiskUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	log.Debugf("resourceDiskUpdate: called for disk_id %d", d.Get("disk_id").(int))
	c := m.(*controller.ControllerCfg)
	w := dc.Warnings{}

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

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

	hasChangeState := false

	switch disk.Status {
	case status.Destroyed, status.Purged:
		d.Set("disk_id", 0)
		d.SetId("")
		return diag.Errorf("The resource cannot be updated because it has been destroyed")
		//return resourceDiskCreate(ctx, d, m)
	case status.Deleted:
		hasChangeState = true
		if err := resourceDiskRestore(ctx, d, m); err != nil {
			return diag.FromErr(err)
		}
	case status.Assigned:
	case status.Modeled:
		return diag.Errorf("The disk is in status: %s, please, contact support for more information", disk.Status)
	case status.Creating:
	case status.Created:
	case status.Allocated:
	case status.Unallocated:
	}

	if hasChangeState {
		disk, err = utilityDiskCheckPresence(ctx, d, m)
		if err != nil {
			d.SetId("")
			return diag.FromErr(err)
		}
	}

	if d.HasChange("storage_policy_id") {
		if err := resourceDiskChangeStoragePolicyID(ctx, d, m); err != nil {
			return diag.FromErr(err)
		}
	}

	if d.HasChange("size_max") {
		oldSize, newSize := d.GetChange("size_max")
		if oldSize.(int) > newSize.(int) {
			return diag.FromErr(fmt.Errorf("resourceDiskUpdate: Disk ID %s - reducing disk size is not allowed", d.Id()))
		}

		log.Debugf("resourceDiskUpdate: resizing disk ID %s - %d GB -> %d GB",
			d.Id(), oldSize.(int), newSize.(int))
		if err := resourceDiskChangeSize(ctx, d, m); err != nil {
			return diag.FromErr(err)
		}
	}

	if d.HasChange("disk_name") {
		if err := resourceDiskChangeDiskName(ctx, d, m); err != nil {
			return diag.FromErr(err)
		}
	}

	if d.HasChange("iotune") {
		if err := resourceDiskChangeIotune(ctx, d, m); err != nil {
			return diag.FromErr(err)
		}
	}

	if d.HasChange("shareable") {
		if err := resourceDiskChangeShareable(ctx, d, m); err != nil {
			return diag.FromErr(err)
		}
	}

	if d.HasChanges("cache", "blk_discard", "block_size") {
		updateReq := disks.UpdateRequest{
			DiskID: uint64(d.Get("disk_id").(int)),
		}
		if d.HasChange("cache") {
			updateReq.Cache = d.Get("cache").(string)
		}
		if d.HasChange("blk_discard") {
			updateReq.BLKDiscard = d.Get("blk_discard").(bool)
		}
		if d.HasChange("block_size") {
			updateReq.BlockSize = d.Get("block_size").(string)
		}
		if _, err := c.CloudBroker().Disks().Update(ctx, updateReq); err != nil {
			return diag.FromErr(err)
		}
	}

	if d.HasChange("node_ids") {
		log.Debugf("resourceDiskUpdate: present for disk %d", d.Get("disk_id"))
		if err := resourceDiskChangeNodes(ctx, d, m, false); err != nil {
			w.Add(err)
		}
		log.Debugf("resourceDiskUpdate: finished present for disk %d", d.Get("disk_id"))
	}

	return append(w.Get(), resourceDiskRead(ctx, d, m)...)
}

func resourceDiskDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	log.Debugf("resourceDiskDelete: called for disk_id %d", d.Get("disk_id").(int))
	c := m.(*controller.ControllerCfg)

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

	req := disks.DeleteRequest{
		DiskID:      disk.ID,
		Detach:      d.Get("detach").(bool),
		Permanently: d.Get("permanently").(bool),
	}

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

	d.SetId("")

	return nil
}

func resourceDiskChangeIotune(ctx context.Context, d *schema.ResourceData, m interface{}) error {
	c := m.(*controller.ControllerCfg)

	iotuneRaw := d.Get("iotune")
	diskId := uint64(d.Get("disk_id").(int))

	iot := iotuneRaw.([]interface{})[0]
	iotune := iot.(map[string]interface{})
	req := disks.LimitIORequest{
		DiskID:           diskId,
		ReadBytesSec:     uint64(iotune["read_bytes_sec"].(int)),
		ReadBytesSecMax:  uint64(iotune["read_bytes_sec_max"].(int)),
		ReadIOPSSec:      uint64(iotune["read_iops_sec"].(int)),
		ReadIOPSSecMax:   uint64(iotune["read_iops_sec_max"].(int)),
		SizeIOPSSec:      uint64(iotune["size_iops_sec"].(int)),
		TotalBytesSec:    uint64(iotune["total_bytes_sec"].(int)),
		TotalBytesSecMax: uint64(iotune["total_bytes_sec_max"].(int)),
		TotalIOPSSecMax:  uint64(iotune["total_iops_sec_max"].(int)),
		TotalIOPSSec:     uint64(iotune["total_iops_sec"].(int)),
		WriteBytesSec:    uint64(iotune["write_bytes_sec"].(int)),
		WriteBytesSecMax: uint64(iotune["write_bytes_sec_max"].(int)),
		WriteIOPSSec:     uint64(iotune["write_iops_sec"].(int)),
		WriteIOPSSecMax:  uint64(iotune["write_iops_sec_max"].(int)),
	}

	if _, ok := iotune["total_iops_sec"]; ok {
		req.IOPS = uint64(iotune["total_iops_sec"].(int))
	}

	_, err := c.CloudBroker().Disks().LimitIO(ctx, req)
	return err
}

func resourceDiskChangeShareable(ctx context.Context, d *schema.ResourceData, m interface{}) error {
	c := m.(*controller.ControllerCfg)

	diskId := uint64(d.Get("disk_id").(int))
	shareable := d.Get("shareable").(bool)

	if shareable {
		_, err := c.CloudBroker().Disks().Share(ctx, disks.ShareRequest{DiskID: diskId})
		return err
	}

	_, err := c.CloudBroker().Disks().Unshare(ctx, disks.UnshareRequest{DiskID: diskId})
	return err
}

func resourceDiskRestore(ctx context.Context, d *schema.ResourceData, m interface{}) error {
	c := m.(*controller.ControllerCfg)

	req := disks.RestoreRequest{
		DiskID: uint64(d.Get("disk_id").(int)),
	}

	_, err := c.CloudBroker().Disks().Restore(ctx, req)
	return err
}

func resourceDiskChangeDiskName(ctx context.Context, d *schema.ResourceData, m interface{}) error {
	c := m.(*controller.ControllerCfg)

	_, err := c.CloudBroker().Disks().Rename(ctx, disks.RenameRequest{
		DiskID: uint64(d.Get("disk_id").(int)),
		Name:   d.Get("disk_name").(string),
	})
	return err
}

func resourceDiskChangeSize(ctx context.Context, d *schema.ResourceData, m interface{}) error {
	c := m.(*controller.ControllerCfg)

	_, err := c.CloudBroker().Disks().Resize2(ctx, disks.ResizeRequest{
		DiskID: uint64(d.Get("disk_id").(int)),
		Size:   uint64(d.Get("size_max").(int)),
	})
	return err
}

func resourceDiskChangeStoragePolicyID(ctx context.Context, d *schema.ResourceData, m interface{}) error {
	c := m.(*controller.ControllerCfg)

	_, err := c.CloudBroker().Disks().ChangeDiskStoragePolicy(ctx, disks.ChangeDiskStoragePolicyRequest{
		DiskID:          uint64(d.Get("disk_id").(int)),
		StoragePolicyID: uint64(d.Get("storage_policy_id").(int)),
	})
	return err
}

func resourceDiskChangeBlockSize(ctx context.Context, d *schema.ResourceData, m interface{}) error {
	c := m.(*controller.ControllerCfg)

	_, err := c.CloudBroker().Disks().Update(ctx, disks.UpdateRequest{
		DiskID:    uint64(d.Get("disk_id").(int)),
		BlockSize: d.Get("block_size").(string),
	})
	return err
}

func resourceDiskChangeNodes(ctx context.Context, d *schema.ResourceData, m interface{}, afterCreate bool) error {
	c := m.(*controller.ControllerCfg)
	diskID := uint64(d.Get("disk_id").(int))
	presentIDs := make([]interface{}, 0)
	var errs error
	var oldNodes, newNodes interface{}

	if afterCreate {
		nodeIDs := d.Get("node_ids").(*schema.Set).List()
		presentIDs = nodeIDs
	} else {
		oldNodes, newNodes = d.GetChange("node_ids")
		nodeIDs := (newNodes.(*schema.Set).Difference(oldNodes.(*schema.Set))).List()
		presentIDs = nodeIDs
	}

	for _, presentID := range presentIDs {
		nodeID := uint64(presentID.(int))

		req := disks.PresentRequest{
			DiskID: diskID,
			NodeID: nodeID,
		}

		_, err := c.CloudBroker().Disks().Present(ctx, req)
		if err != nil {
			errs = errors.Join(err)
		}
	}

	if afterCreate {
		return errs
	}

	depresentIDs := (oldNodes.(*schema.Set).Difference(newNodes.(*schema.Set))).List()
	if len(depresentIDs) > 0 {
		for _, depresentID := range depresentIDs {
			nodeID := uint64(depresentID.(int))

			req := disks.DepresentRequest{
				DiskID: diskID,
				NodeID: nodeID,
			}

			_, err := c.CloudBroker().Disks().Depresent(ctx, req)
			if err != nil {
				errs = errors.Join(err)
			}
		}
	}

	return errs
}

func ResourceDisk() *schema.Resource {
	return &schema.Resource{
		SchemaVersion: 2,

		CreateContext: resourceDiskCreate,
		ReadContext:   resourceDiskRead,
		UpdateContext: resourceDiskUpdate,
		DeleteContext: resourceDiskDelete,

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

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

		Schema: resourceDiskSchemaMake(),
		StateUpgraders: []schema.StateUpgrader{
			{
				Type:    resourceDiskV1().CoreConfigSchema().ImpliedType(),
				Upgrade: resourceDiskUpgradeV1,
				Version: 1,
			},
		},
	}
}
