/*
Copyright (c) 2019-2023 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 image

import (
	"context"
	"strconv"

	"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/image"
	"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 resourceCDROMImageCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	log.Debugf("resourceCDROMImageCreate: called for image %s", d.Get("name").(string))
	c := m.(*controller.ControllerCfg)
	req := image.CreateCDROMImageRequest{
		Name:            d.Get("name").(string),
		URL:             d.Get("url").(string),
		StoragePolicyID: uint64(d.Get("storage_policy_id").(int)),
	}

	if username, ok := d.GetOk("username_dl"); ok {
		req.UsernameDL = username.(string)
	}
	if password, ok := d.GetOk("password_dl"); ok {
		req.PasswordDl = password.(string)
	}
	if accountId, ok := d.GetOk("account_id"); ok {
		req.AccountID = uint64(accountId.(int))
	}
	if sepId, ok := d.GetOk("sep_id"); ok {
		req.SEPID = uint64(sepId.(int))
	}
	if poolName, ok := d.GetOk("pool_name"); ok {
		req.PoolName = poolName.(string)
	}

	imageId, err := c.CloudBroker().Image().CreateCDROMImage(ctx, req)
	if err != nil {
		return diag.FromErr(err)
	}

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

	return resourceImageRead(ctx, d, m)
}

func resourceCDROMImageRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	log.Debugf("resourceCDROMImageRead: called for %s id: %s", d.Get("name").(string), d.Id())

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

	switch img.Status {
	case status.Modeled:
		return diag.Errorf("The image is in status: %s, please, contact support for more information", img.Status)
	case status.Destroyed, status.Purged:
		d.SetId("")
		return diag.Errorf("The resource cannot be updated because it has been destroyed")
	}

	flattenImage(d, img)

	return nil
}

func resourceCDROMImageDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	log.Debugf("resourceCDROMImageDelete: called for %s, id: %s", d.Get("name").(string), d.Id())

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

	c := m.(*controller.ControllerCfg)
	req := image.DeleteCDROMImageRequest{
		ImageID: imageData.ID,
	}

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

	d.SetId("")

	return nil
}

func resourceCDROMImageUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	log.Debugf("resourceCDROMImageEdit: called for %s, id: %s", d.Get("name").(string), d.Id())

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

	switch img.Status {
	case status.Modeled:
		return diag.Errorf("The image is in status: %s, please, contact support for more information", img.Status)
	case status.Destroyed, status.Purged:
		d.SetId("")
		return diag.Errorf("The resource cannot be updated because it has been destroyed")
	}

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

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

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

	if d.HasChanges("name", "password_dl", "username_dl", "account_id", "bootable", "hot_resize") {
		err := resourceImageCDROMEdit(ctx, d, m)
		if err != nil {
			return diag.FromErr(err)
		}
	}

	return nil
}

func resourceImageCDROMEdit(ctx context.Context, d *schema.ResourceData, m interface{}) error {
	log.Debugf("resourceImageEdit: called for %s, id: %s", d.Get("name").(string), d.Id())
	c := m.(*controller.ControllerCfg)
	req := image.EditRequest{}

	req.ImageID = uint64(d.Get("image_id").(int))
	if d.HasChange("name") {
		req.Name = d.Get("name").(string)
	}
	if d.HasChange("username_dl") {
		req.Username = d.Get("username_dl").(string)
	}
	if d.HasChange("password_dl") {
		req.Password = d.Get("password_dl").(string)
	}
	if d.HasChange("account_id") {
		req.AccountID = uint64(d.Get("account_id").(int))
	}
	if d.HasChange("bootable") {
		req.Bootable = d.Get("bootable").(bool)
	}
	if d.HasChange("hot_resize") {
		req.HotResize = d.Get("hot_resize").(bool)
	}

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

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

		CreateContext: resourceCDROMImageCreate,
		ReadContext:   resourceCDROMImageRead,
		UpdateContext: resourceCDROMImageUpdate,
		DeleteContext: resourceCDROMImageDelete,

		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: resourceCDROMImageSchemaMake(),
		StateUpgraders: []schema.StateUpgrader{
			{
				Type:    resourceCDROMImageV1().CoreConfigSchema().ImpliedType(),
				Upgrade: resourcePresentTOUpgradeV1,
				Version: 1,
			},
		},
	}
}
