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

import (
	"context"
	"fmt"
	"strconv"

	log "github.com/sirupsen/logrus"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/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"
)

func resourceDiskCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	c := m.(*controller.ControllerCfg)
	req := disks.CreateRequest{}

	haveAccount, err := existAccountID(ctx, d, m)
	if err != nil {
		return diag.FromErr(err)
	}
	if !haveAccount {
		return diag.Errorf("resourceDiskCreate: can't create Disk because AccountID %d is not allowed or does not exist", d.Get("account_id").(int))
	}

	req.AccountID = uint64(d.Get("account_id").(int))
	req.Name = d.Get("disk_name").(string)
	req.StoragePolicyID = uint64(d.Get("storage_policy_id").(int))
	req.Size = uint64(d.Get("size_max").(int))

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

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

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

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

	d.SetId(strconv.FormatUint(diskId, 10))

	if iotuneRaw, ok := d.GetOk("iotune"); ok {
		iot := iotuneRaw.([]interface{})[0]
		iotune := iot.(map[string]interface{})
		req := disks.LimitIORequest{
			DiskID:           diskId,
			IOPS:             uint64(iotune["total_iops_sec"].(int)),
			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)),
		}

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

	if shareable := d.Get("shareable"); shareable.(bool) == true {
		req := disks.ShareRequest{
			DiskID: diskId,
		}

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

	return resourceDiskRead(ctx, d, m)
}

func resourceDiskRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	// c := m.(*controller.ControllerCfg)
	warnings := 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 updated because it has been destroyed")
		// return resourceDiskCreate(ctx, d, m)
	case status.Deleted:
		// hasChangeState = true
		// req := disks.RestoreRequest{
		// 	DiskID: disk.ID,
		// }

		// if reason, ok := d.GetOk("reason"); ok {
		// 	req.Reason = reason.(string)
		// } else {
		// 	req.Reason = "Terraform automatic restore"
		// }

		// _, err := c.CloudAPI().Disks().Restore(ctx, req)
		// if err != nil {
		// 	warnings.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 warnings.Get()
}

func resourceDiskUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	c := m.(*controller.ControllerCfg)
	warnings := dc.Warnings{}

	haveAccount, err := existAccountID(ctx, d, m)
	if err != nil {
		return diag.FromErr(err)
	}
	if !haveAccount {
		return diag.Errorf("resourceDiskUpdate: can't update Disk because AccountID %d is not allowed or does not exist", d.Get("account_id").(int))
	}

	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
		req := disks.RestoreRequest{
			DiskID: disk.ID,
		}

		_, err := c.CloudAPI().Disks().Restore(ctx, req)
		if err != nil {
			warnings.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)
		}
	}

	if d.HasChange("storage_policy_id") {
		req := disks.ChangeDiskStoragePolicyRequest{
			DiskID:          disk.ID,
			StoragePolicyID: uint64(d.Get("storage_policy_id").(int)),
		}

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

	if d.HasChange("size_max") {
		oldSize, newSize := d.GetChange("size_max")
		if oldSize.(int) < newSize.(int) {
			log.Debugf("resourceDiskUpdate: resizing disk ID %s - %d GB -> %d GB",
				d.Id(), oldSize.(int), newSize.(int))
			req := disks.ResizeRequest{
				DiskID: disk.ID,
				Size:   uint64(newSize.(int)),
			}

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

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

	if d.HasChange("disk_name") {
		req := disks.RenameRequest{
			DiskID: disk.ID,
			Name:   d.Get("disk_name").(string),
		}

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

	if d.HasChange("iotune") {
		iot := d.Get("iotune").([]interface{})[0]
		iotune := iot.(map[string]interface{})
		req := disks.LimitIORequest{
			DiskID:           disk.ID,
			IOPS:             uint64(iotune["total_iops_sec"].(int)),
			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)),
		}

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

	if d.HasChange("shareable") {
		oldShare, newShare := d.GetChange("shareable")
		if oldShare.(bool) == false && newShare.(bool) == true {
			req := disks.ShareRequest{DiskID: disk.ID}

			_, err := c.CloudAPI().Disks().Share(ctx, req)
			if err != nil {
				return diag.FromErr(err)
			}
		}
		if oldShare.(bool) == true && newShare.(bool) == false {
			req := disks.UnshareRequest{DiskID: disk.ID}

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

	return resourceDiskRead(ctx, d, m)
}

func resourceDiskDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	disk, err := utilityDiskCheckPresence(ctx, d, m)
	if err != nil {
		d.SetId("")
		return diag.FromErr(err)
	}
	if disk.Status == status.Destroyed || disk.Status == status.Purged {
		return nil
	}

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

	c := m.(*controller.ControllerCfg)
	_, err = c.CloudAPI().Disks().Delete(ctx, req)
	if err != nil {
		return diag.FromErr(err)
	}

	d.SetId("")

	return nil
}

func resourceDiskSchemaMake() map[string]*schema.Schema {
	rets := map[string]*schema.Schema{
		"account_id": {
			Type:     schema.TypeInt,
			Required: true,
			//ForceNew:    true,
			Description: "The unique ID of the subscriber-owner of the disk",
		},
		"storage_policy_id": {
			Type:        schema.TypeInt,
			Required:    true,
			Description: "ID storage policy under which the disk will be created",
		},
		"created_by": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"deleted_by": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"disk_name": {
			Type:        schema.TypeString,
			Required:    true,
			Description: "Name of disk",
		},
		"size_max": {
			Type:        schema.TypeInt,
			Required:    true,
			Description: "Size in GB",
		},
		"pool": {
			Type:        schema.TypeString,
			Optional:    true,
			Computed:    true,
			Description: "Pool for disk location",
		},
		"sep_id": {
			Type:        schema.TypeInt,
			Optional:    true,
			Computed:    true,
			Description: "Storage endpoint provider ID to create disk",
		},
		"desc": {
			Type:        schema.TypeString,
			Optional:    true,
			Computed:    true,
			Description: "Description of disk",
		},
		"detach": {
			Type:        schema.TypeBool,
			Optional:    true,
			Default:     false,
			Description: "Detaching the disk from compute",
		},
		"permanently": {
			Type:        schema.TypeBool,
			Optional:    true,
			Default:     false,
			Description: "Whether to completely delete the disk, works only with non attached disks",
		},
		"shareable": {
			Type:     schema.TypeBool,
			Optional: true,
			Computed: true,
		},
		"iotune": {
			Type:     schema.TypeList,
			Optional: true,
			MaxItems: 1,
			Computed: true,
			Elem: &schema.Resource{
				Schema: map[string]*schema.Schema{
					"read_bytes_sec": {
						Type:        schema.TypeInt,
						Optional:    true,
						Computed:    true,
						Description: "Number of bytes to read per second",
					},
					"read_bytes_sec_max": {
						Type:        schema.TypeInt,
						Optional:    true,
						Computed:    true,
						Description: "Maximum number of bytes to read",
					},
					"read_iops_sec": {
						Type:        schema.TypeInt,
						Optional:    true,
						Computed:    true,
						Description: "Number of io read operations per second",
					},
					"read_iops_sec_max": {
						Type:        schema.TypeInt,
						Optional:    true,
						Computed:    true,
						Description: "Maximum number of io read operations",
					},
					"size_iops_sec": {
						Type:        schema.TypeInt,
						Optional:    true,
						Computed:    true,
						Description: "Size of io operations",
					},
					"total_bytes_sec": {
						Type:        schema.TypeInt,
						Optional:    true,
						Computed:    true,
						Description: "Total size bytes per second",
					},
					"total_bytes_sec_max": {
						Type:        schema.TypeInt,
						Optional:    true,
						Computed:    true,
						Description: "Maximum total size of bytes per second",
					},
					"total_iops_sec": {
						Type:        schema.TypeInt,
						Optional:    true,
						Computed:    true,
						Description: "Total number of io operations per second",
					},
					"total_iops_sec_max": {
						Type:        schema.TypeInt,
						Optional:    true,
						Computed:    true,
						Description: "Maximum total number of io operations per second",
					},
					"write_bytes_sec": {
						Type:        schema.TypeInt,
						Optional:    true,
						Computed:    true,
						Description: "Number of bytes to write per second",
					},
					"write_bytes_sec_max": {
						Type:        schema.TypeInt,
						Optional:    true,
						Computed:    true,
						Description: "Maximum number of bytes to write per second",
					},
					"write_iops_sec": {
						Type:        schema.TypeInt,
						Optional:    true,
						Computed:    true,
						Description: "Number of write operations per second",
					},
					"write_iops_sec_max": {
						Type:        schema.TypeInt,
						Optional:    true,
						Computed:    true,
						Description: "Maximum number of write operations per second",
					},
				},
			},
		},
		"present_to": {
			Type:     schema.TypeMap,
			Computed: true,
			Elem: &schema.Schema{
				Type: schema.TypeInt,
			},
		},
		"disk_id": {
			Type:        schema.TypeInt,
			Computed:    true,
			Description: "Disk ID. Duplicates the value of the ID parameter",
		},
		"account_name": {
			Type:        schema.TypeString,
			Computed:    true,
			Description: "The name of the subscriber '(account') to whom this disk belongs",
		},
		"acl": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"cache": {
			Type:     schema.TypeString,
			Computed: true,
		},
		// "boot_partition": {
		// 	Type:        schema.TypeInt,
		// 	Computed:    true,
		// 	Description: "Number of disk partitions",
		// },
		"computes": {
			Type:     schema.TypeList,
			Computed: true,
			Elem: &schema.Resource{
				Schema: map[string]*schema.Schema{
					"compute_id": {
						Type:     schema.TypeString,
						Computed: true,
					},
					"compute_name": {
						Type:     schema.TypeString,
						Computed: true,
					},
				},
			},
		},
		"created_time": {
			Type:        schema.TypeInt,
			Computed:    true,
			Description: "Created time",
		},
		"deleted_time": {
			Type:        schema.TypeInt,
			Computed:    true,
			Description: "Deleted time",
		},
		"destruction_time": {
			Type:        schema.TypeInt,
			Computed:    true,
			Description: "Time of final deletion",
		},
		"devicename": {
			Type:        schema.TypeString,
			Computed:    true,
			Description: "Name of the device",
		},
		"gid": {
			Type:        schema.TypeInt,
			Computed:    true,
			Description: "ID of the grid (platform)",
		},
		// "disk_path": {
		// 	Type:        schema.TypeString,
		// 	Computed:    true,
		// 	Description: "Disk path",
		// },
		// "guid": {
		// 	Type:        schema.TypeInt,
		// 	Computed:    true,
		// 	Description: "Disk ID on the storage side",
		// },
		"image_id": {
			Type:        schema.TypeInt,
			Computed:    true,
			Description: "Image ID",
		},
		"images": {
			Type:     schema.TypeList,
			Computed: true,
			Elem: &schema.Schema{
				Type: schema.TypeInt,
			},
			Description: "IDs of images using the disk",
		},
		"independent": {
			Type:     schema.TypeBool,
			Computed: true,
		},
		// "iqn": {
		// 	Type:        schema.TypeString,
		// 	Computed:    true,
		// 	Description: "Disk IQN",
		// },
		// "login": {
		// 	Type:        schema.TypeString,
		// 	Computed:    true,
		// 	Description: "Login to access the disk",
		// },
		// "milestones": {
		// 	Type:        schema.TypeInt,
		// 	Computed:    true,
		// 	Description: "Milestones",
		// },
		"machine_id": {
			Type:     schema.TypeInt,
			Computed: true,
		},
		"machine_name": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"order": {
			Type:        schema.TypeInt,
			Computed:    true,
			Description: "Disk order",
		},
		"params": {
			Type:        schema.TypeString,
			Computed:    true,
			Description: "Disk params",
		},
		"parent_id": {
			Type:        schema.TypeInt,
			Computed:    true,
			Description: "ID of the parent disk",
		},
		// "passwd": {
		// 	Type:        schema.TypeString,
		// 	Computed:    true,
		// 	Description: "Password to access the disk",
		// },
		"pci_slot": {
			Type:        schema.TypeInt,
			Computed:    true,
			Description: "ID of the pci slot to which the disk is connected",
		},
		// "purge_attempts": {
		// 	Type:        schema.TypeInt,
		// 	Computed:    true,
		// 	Description: "Number of deletion attempts",
		// },
		"provision": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"purge_time": {
			Type:        schema.TypeInt,
			Computed:    true,
			Description: "Time of the last deletion attempt",
		},
		"replication": {
			Type:     schema.TypeList,
			Computed: true,
			Elem: &schema.Resource{
				Schema: map[string]*schema.Schema{
					"disk_id": {
						Type:     schema.TypeInt,
						Computed: true,
					},
					"pool_id": {
						Type:     schema.TypeString,
						Computed: true,
					},
					"role": {
						Type:     schema.TypeString,
						Computed: true,
					},
					"self_volume_id": {
						Type:     schema.TypeString,
						Computed: true,
					},
					"storage_id": {
						Type:     schema.TypeString,
						Computed: true,
					},
					"volume_id": {
						Type:     schema.TypeString,
						Computed: true,
					},
				},
			},
			Description: "Replication status",
		},
		// "reality_device_number": {
		// 	Type:        schema.TypeInt,
		// 	Computed:    true,
		// 	Description: "Reality device number",
		// },
		// "reference_id": {
		// 	Type:        schema.TypeString,
		// 	Computed:    true,
		// 	Description: "ID of the reference to the disk",
		// },
		"res_id": {
			Type:        schema.TypeString,
			Computed:    true,
			Description: "Resource ID",
		},
		"res_name": {
			Type:        schema.TypeString,
			Computed:    true,
			Description: "Name of the resource",
		},
		"role": {
			Type:        schema.TypeString,
			Computed:    true,
			Description: "Disk role",
		},
		"sep_type": {
			Type:        schema.TypeString,
			Computed:    true,
			Description: "Type SEP. Defines the type of storage system and contains one of the values set in the cloud platform",
		},
		"size_used": {
			Type:        schema.TypeFloat,
			Computed:    true,
			Description: "Number of used space, in GB",
		},
		"snapshots": {
			Type:     schema.TypeList,
			Computed: true,
			Elem: &schema.Resource{
				Schema: map[string]*schema.Schema{
					"guid": {
						Type:        schema.TypeString,
						Computed:    true,
						Description: "ID of the snapshot",
					},
					"label": {
						Type:        schema.TypeString,
						Computed:    true,
						Description: "Name of the snapshot",
					},
					"res_id": {
						Type:        schema.TypeString,
						Computed:    true,
						Description: "Reference to the snapshot",
					},
					"snap_set_guid": {
						Type:        schema.TypeString,
						Computed:    true,
						Description: "The set snapshot ID",
					},
					"snap_set_time": {
						Type:        schema.TypeInt,
						Computed:    true,
						Description: "The set time of the snapshot",
					},
					"timestamp": {
						Type:        schema.TypeInt,
						Computed:    true,
						Description: "Snapshot time",
					},
				},
			},
		},
		"status": {
			Type:        schema.TypeString,
			Computed:    true,
			Description: "Disk status",
		},
		"tech_status": {
			Type:        schema.TypeString,
			Computed:    true,
			Description: "Technical status of the disk",
		},
		"vmid": {
			Type:        schema.TypeInt,
			Computed:    true,
			Description: "Virtual Machine ID (Deprecated)",
		},
		"updated_by": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"updated_time": {
			Type:     schema.TypeInt,
			Computed: true,
		},
		"to_clean": {
			Type:     schema.TypeBool,
			Computed: true,
		},
		"blk_discard": {
			Type:        schema.TypeBool,
			Computed:    true,
			Description: "Flag indicating whether blk-discard is enabled for the disk",
		},
		"block_size": {
			Type:     schema.TypeString,
			Computed: true,
		},
	}

	return rets
}

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,
			},
		},
	}
}
