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

import (
	"context"
	"fmt"
	"strings"
	"time"

	//"log"
	"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/account"
	"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 resourceAccountCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	log.Debugf("resourseAccountCreate")

	c := m.(*controller.ControllerCfg)

	req := account.CreateRequest{
		Name:     d.Get("account_name").(string),
		Username: d.Get("username").(string),
	}

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

	if zoneID, ok := d.GetOk("default_zone_id"); ok {
		req.DefaultZoneID = uint64(zoneID.(int))
	}

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

	if sendAccessEmails, ok := d.GetOk("send_access_emails"); ok {
		req.SendAccessEmails = sendAccessEmails.(bool)
	}

	if uniqPools, ok := d.GetOk("uniq_pools"); ok {
		uniqPools := uniqPools.([]interface{})
		for _, pool := range uniqPools {
			req.UniqPools = append(req.UniqPools, pool.(string))
		}
	}

	if zones, ok := d.GetOk("zone_ids"); ok {
		zones := zones.([]interface{})
		for _, zone := range zones {
			req.ZoneIDs = append(req.ZoneIDs, uint64(zone.(int)))
		}
	}

	if resLimits, ok := d.GetOk("resource_limits"); ok {
		resLimits := resLimits.([]interface{})[0]
		resLimitsConv := resLimits.(map[string]interface{})
		if resLimitsConv["cu_m"] != nil {
			maxMemCap := int64(resLimitsConv["cu_m"].(float64))
			if maxMemCap == 0 {
				req.MaxMemoryCapacity = -1
			} else {
				req.MaxMemoryCapacity = maxMemCap
			}
		}
		if resLimitsConv["cu_dm"] != nil {
			maxDiskCap := int64(resLimitsConv["cu_dm"].(float64))
			if maxDiskCap == 0 {
				req.MaxVDiskCapacity = -1
			} else {
				req.MaxVDiskCapacity = maxDiskCap
			}
		}
		if resLimitsConv["cu_c"] != nil {
			maxCPUCap := int64(resLimitsConv["cu_c"].(float64))
			if maxCPUCap == 0 {
				req.MaxCPUCapacity = -1
			} else {
				req.MaxCPUCapacity = maxCPUCap
			}
		}
		if resLimitsConv["cu_i"] != nil {
			maxNumPublicIP := int64(resLimitsConv["cu_i"].(float64))
			if maxNumPublicIP == 0 {
				req.MaxNumPublicIP = -1
			} else {
				req.MaxNumPublicIP = maxNumPublicIP
			}
		}
		if resLimitsConv["gpu_units"] != nil {
			gpuUnits := int64(resLimitsConv["gpu_units"].(float64))
			if gpuUnits == 0 {
				req.GPUUnits = -1
			} else {
				req.GPUUnits = gpuUnits
			}
		}
	}

	if stPolicy, ok := d.GetOk("storage_policy"); ok {
		sp := stPolicy.(*schema.Set).List()
		storagePolicies := make([]account.StoragePolicy, 0)
		for _, elem := range sp {
			stPolicyVal := elem.(map[string]interface{})

			reqStPolicy := account.StoragePolicy{
				ID:    uint64(stPolicyVal["id"].(int)),
				Limit: stPolicyVal["limit"].(int),
			}

			storagePolicies = append(storagePolicies, reqStPolicy)
		}
		req.StoragePolicies = storagePolicies

	}

	if compFeaturesInterface, ok := d.GetOk("compute_features"); ok {
		compFeaturesInterfaces := compFeaturesInterface.(*schema.Set).List()

		compFeatures := make([]string, 0, len(compFeaturesInterfaces))

		for _, item := range compFeaturesInterfaces {
			compFeatures = append(compFeatures, item.(string))
		}

		req.ComputeFeatures = compFeatures
	}

	accountId, err := c.CloudBroker().Account().Create(ctx, req)
	if err != nil {
		return diag.FromErr(err)
	}

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

	var w dc.Warnings

	if users, ok := d.GetOk("users"); ok {
		addedUsers := users.([]interface{})

		for _, user := range addedUsers {
			userConv := user.(map[string]interface{})

			req := account.AddUserRequest{
				AccountID:  accountId,
				Username:   userConv["user_id"].(string),
				AccessType: userConv["access_type"].(string),
			}

			_, err := c.CloudBroker().Account().AddUser(ctx, req)
			if err != nil {
				w.Add(err)
			}
		}
	}

	if cpuAllocationParameter, ok := d.GetOk("cpu_allocation_parameter"); ok {
		cpuAllocationParameter := cpuAllocationParameter.(string)

		req := account.SetCPUAllocationParameterRequest{
			AccountID:   accountId,
			StrictLoose: cpuAllocationParameter,
		}

		log.Debugf("setting account cpu allocation parameter")
		_, err := c.CloudBroker().Account().SetCPUAllocationParameter(ctx, req)
		if err != nil {
			w.Add(err)
		}
	}

	if cpuAllocationRatio, ok := d.GetOk("cpu_allocation_ratio"); ok {
		cpuAllocationRatio := cpuAllocationRatio.(float64)

		req := account.SetCPUAllocationRatioRequest{
			AccountID: accountId,
			Ratio:     cpuAllocationRatio,
		}

		log.Debugf("setting account cpu allocation ratio")
		_, err := c.CloudBroker().Account().SetCPUAllocationRatio(ctx, req)
		if err != nil {
			w.Add(err)
		}
	}

	if !d.Get("enable").(bool) {
		_, err := c.CloudBroker().Account().Disable(ctx, account.DisableRequest{
			AccountID: accountId,
		})

		if err != nil {
			w.Add(err)
		}
	}

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

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

func resourceAccountRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	log.Debugf("resourceAccountRead")

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

	flattenResourceAccount(d, acc)

	return nil
}

func resourceAccountDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	log.Debugf("resourceAccountDelete")

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

	c := m.(*controller.ControllerCfg)
	req := account.DeleteRequest{
		AccountID:   accountData.ID,
		Permanently: d.Get("permanently").(bool),
		Name:        d.Get("account_name").(string),
	}

	taskID, err := c.CloudBroker().Account().Delete(ctx, req)
	if err != nil {
		return diag.FromErr(err)
	}

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

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

		log.Debugf("resourceAccountDelete: delete account - %s", task.Stage)

		if task.Completed {
			if task.Error != "" {
				return diag.FromErr(fmt.Errorf("cannot delete account: %v", task.Error))
			}
			break
		}
	}

	d.SetId("")

	return nil
}

func resourceAccountUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	log.Debugf("resourceAccountUpdate")

	c := m.(*controller.ControllerCfg)

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

	accountId, _ := strconv.ParseUint(d.Id(), 10, 64)

	hasChanged := false

	switch acc.Status {
	case status.Destroyed:
		d.SetId("")
		// return resourceAccountCreate(ctx, d, m)
		return diag.Errorf("The resource cannot be updated because it has been destroyed")
	case status.Destroying:
		return diag.Errorf("The account is in progress with status: %s", acc.Status)
	case status.Deleted:
		if d.Get("restore").(bool) {
			taskID, err := c.CloudBroker().Account().Restore(ctx, account.RestoreRequest{
				AccountID: accountId,
			})

			if err != nil {
				return diag.FromErr(err)
			}

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

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

				log.Debugf("resourceAccountUpdate: restore account - %s", task.Stage)

				if task.Completed {
					if task.Error != "" {
						return diag.FromErr(fmt.Errorf("cannot restore account: %v", task.Error))
					}
					break
				}
			}
			if _, ok := d.GetOk("enable"); ok {
				if err := utilityAccountEnableUpdate(ctx, d, m, acc); err != nil {
					return diag.FromErr(err)
				}
			}
			hasChanged = true
		}
	case status.Disabled:
		log.Debugf("The account is in status: %s, troubles may occur with update. Please, enable account first.", acc.Status)
	case status.Confirmed:
	}

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

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

	needUpdateSP := false
	if d.HasChange("storage_policy") {
		needUpdate, err := utilityAccountUpdateStPolicy(ctx, d, m)
		if err != nil {
			return diag.FromErr(err)
		}
		needUpdateSP = needUpdate
	}

	if d.HasChanges("account_name", "send_access_emails", "uniq_pools", "resource_limits", "desc", "default_zone_id") || needUpdateSP {
		if err := utilityAccountUpdate(ctx, d, m); err != nil {
			return diag.FromErr(err)
		}
	}

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

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

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

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

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

	if d.HasChange("zone_ids") {
		old, new := d.GetChange("zone_ids")

		toRemoveSet := old.(*schema.Set).Difference(new.(*schema.Set))
		toAddSet := new.(*schema.Set).Difference(old.(*schema.Set))

		if len(toAddSet.List()) > 0 {
			if err := utilityZoneIDsAdd(ctx, d, m, toAddSet); err != nil {
				return diag.FromErr(err)
			}
		}
		if len(toRemoveSet.List()) > 0 {
			if err := utilityZoneIDsRemove(ctx, d, m, toRemoveSet); err != nil {
				return diag.FromErr(err)
			}
		}

	}

	return resourceAccountRead(ctx, d, m)
}

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

		CreateContext: resourceAccountCreate,
		ReadContext:   resourceAccountRead,
		UpdateContext: resourceAccountUpdate,
		DeleteContext: resourceAccountDelete,

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