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

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

	"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/cloudapi/account"
	"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/status"
)

func resourceAccountCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	return diag.Errorf(
		"Only users with admin privileges are able to create accounts. Contact your platform administrator.\nUse 'terraform import decort_account.<NAME> <ID>' command to import existing account configuration")
}

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

	// c := m.(*controller.ControllerCfg)

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

	hasChanged := false

	switch acc.Status {
	case status.Destroyed:
		d.SetId("")
		return diag.Errorf("The resource cannot be updated because it has been destroyed")
		// return resourceAccountCreate(ctx, d, m)
	case status.Destroying:
		return diag.Errorf("The account is in progress with status: %s", acc.Status)
	case status.Deleted:
		// id, _ := strconv.ParseUint(d.Id(), 10, 64)

		// req := account.RestoreRequest{
		// 	AccountID: id,
		// }

		// _, err := c.CloudAPI().Account().Restore(ctx, req)
		// if 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)
		}
	}

	flattenAccountResource(d, *acc)

	return nil
}

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

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

	req := account.DeleteRequest{
		AccountID:   uint64(d.Get("account_id").(int)),
		Permanently: d.Get("permanently").(bool),
	}

	taskID, err := c.CloudAPI().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.CloudAPI().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 diag.Errorf("The resource cannot be updated because it has been destroyed")
		// return resourceAccountCreate(ctx, d, m)
	case status.Destroying:
		return diag.Errorf("The account is in progress with status: %s", acc.Status)
	case status.Deleted:
		if d.Get("restore").(bool) {
			req := account.RestoreRequest{
				AccountID: accountId,
			}

			taskID, err := c.CloudAPI().Account().Restore(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.CloudAPI().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
				}
			}

			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") {
		reqSwitch := account.DisableEnableRequest{
			AccountID: accountId,
		}
		enable := d.Get("enable").(bool)

		if enable {

			_, err := c.CloudAPI().Account().Enable(ctx, reqSwitch)
			if err != nil {
				return diag.FromErr(err)

			}
		} else {

			_, err := c.CloudAPI().Account().Disable(ctx, reqSwitch)
			if err != nil {
				return diag.FromErr(err)
			}

		}
	}

	req := account.UpdateRequest{
		AccountID: accountId,
	}

	updated := false

	if d.HasChange("account_name") {
		req.Name = d.Get("account_name").(string)
		updated = true
	}

	if d.HasChange("desc") {
		req.Description = d.Get("desc").(string)
		updated = true
	}

	if d.HasChange("resource_limits") {
		resLimit := d.Get("resource_limits").([]interface{})[0]
		resLimitConv := resLimit.(map[string]interface{})

		if resLimitConv["cu_m"] != nil {
			maxMemCap := int(resLimitConv["cu_m"].(float64))
			if maxMemCap == 0 {
				req.MaxMemoryCapacity = -1
			} else {
				req.MaxMemoryCapacity = int64(maxMemCap)
			}
			updated = true
		}
		if resLimitConv["cu_d"] != nil {
			maxDiskCap := int(resLimitConv["cu_d"].(float64))
			if maxDiskCap == 0 {
				req.MaxVDiskCapacity = -1
			} else {
				req.MaxVDiskCapacity = int64(maxDiskCap)
			}
			updated = true
		}
		if resLimitConv["cu_c"] != nil {
			maxCPUCap := int(resLimitConv["cu_c"].(float64))
			if maxCPUCap == 0 {
				req.MaxCPUCapacity = -1
			} else {
				req.MaxCPUCapacity = int64(maxCPUCap)
			}
			updated = true
		}
		if resLimitConv["cu_i"] != nil {
			maxNumPublicIP := int(resLimitConv["cu_i"].(float64))
			if maxNumPublicIP == 0 {
				req.MaxNumPublicIP = -1
			} else {
				req.MaxNumPublicIP = int64(maxNumPublicIP)
			}
			updated = true
		}
		if resLimitConv["gpu_units"] != nil {
			gpuUnits := int(resLimitConv["gpu_units"].(float64))
			if gpuUnits == 0 {
				req.GPUUnits = -1
			} else {
				req.GPUUnits = int64(gpuUnits)
			}
			updated = true
		}
	}

	if d.HasChange("send_access_emails") {
		req.SendAccessEmails = d.Get("send_access_emails").(bool)
		updated = true
	}

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

	if d.HasChange("default_zone_id") {
		req.DefaultZoneID = uint64(d.Get("default_zone_id").(int))
		updated = true
	}

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

	if d.HasChange("users") {
		deletedUsers := make([]interface{}, 0)
		addedUsers := make([]interface{}, 0)
		updatedUsers := make([]interface{}, 0)

		old, new_ := d.GetChange("users")
		oldConv := old.([]interface{})
		newConv := new_.([]interface{})
		for _, el := range oldConv {
			if !isContainsUser(newConv, el) {
				deletedUsers = append(deletedUsers, el)
			}
		}
		for _, el := range newConv {
			if !isContainsUser(oldConv, el) {
				duplicate := false
				for _, user := range acc.ACL {
					if user.UgroupID == el.(map[string]interface{})["user_id"].(string) {
						duplicate = true
					}
				}
				if !duplicate {
					addedUsers = append(addedUsers, el)
				}
			} else {
				if isChangedUser(oldConv, el) {
					updatedUsers = append(updatedUsers, el)
				}
			}
		}

		if len(deletedUsers) > 0 {
			for _, user := range deletedUsers {
				userConv := user.(map[string]interface{})

				req := account.DeleteUserRequest{
					AccountID: accountId,
					UserID:    userConv["user_id"].(string),
				}
				_, err := c.CloudAPI().Account().DeleteUser(ctx, req)
				if err != nil {
					return diag.FromErr(err)
				}
			}
		}

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

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

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

		if len(updatedUsers) > 0 {
			for _, user := range updatedUsers {
				userConv := user.(map[string]interface{})

				req := account.UpdateUserRequest{
					AccountID:  accountId,
					UserID:     userConv["user_id"].(string),
					AccessType: strings.ToUpper(userConv["access_type"].(string)),
				}

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

	}

	return resourceAccountRead(ctx, d, m)
}

func isContainsUser(els []interface{}, el interface{}) bool {
	for _, elOld := range els {
		elOldConv := elOld.(map[string]interface{})
		elConv := el.(map[string]interface{})
		if elOldConv["user_id"].(string) == elConv["user_id"].(string) {
			return true
		}
	}
	return false
}

func isChangedUser(els []interface{}, el interface{}) bool {
	for _, elOld := range els {
		elOldConv := elOld.(map[string]interface{})
		elConv := el.(map[string]interface{})
		if elOldConv["user_id"].(string) == elConv["user_id"].(string) &&
			(!strings.EqualFold(elOldConv["access_type"].(string), elConv["access_type"].(string))) {
			return true
		}
	}
	return false
}

func resourceAccountSchemaMake() map[string]*schema.Schema {
	return map[string]*schema.Schema{
		"account_name": {
			Type:        schema.TypeString,
			Required:    true,
			Description: "account name",
		},
		"desc": {
			Type:        schema.TypeString,
			Optional:    true,
			Description: "description",
		},
		"emailaddress": {
			Type:        schema.TypeString,
			Optional:    true,
			Description: "email",
		},
		"send_access_emails": {
			Type:        schema.TypeBool,
			Optional:    true,
			Description: "if true send emails when a user is granted access to resources",
		},
		"users": {
			Type:     schema.TypeList,
			Optional: true,
			Elem: &schema.Resource{
				Schema: map[string]*schema.Schema{
					"user_id": {
						Type:     schema.TypeString,
						Required: true,
					},
					"access_type": {
						Type:     schema.TypeString,
						Required: true,
					},
				},
			},
		},
		"default_zone_id": {
			Type:        schema.TypeInt,
			Optional:    true,
			Computed:    true,
			Description: "email",
		},
		"zone_ids": {
			Type:     schema.TypeList,
			Computed: true,
			Elem: &schema.Schema{
				Type: schema.TypeInt,
			},
		},
		"restore": {
			Type:        schema.TypeBool,
			Optional:    true,
			Description: "restore a deleted account",
		},
		"permanently": {
			Type:        schema.TypeBool,
			Optional:    true,
			Default:     false,
			Description: "whether to completely delete the account",
		},
		"enable": {
			Type:        schema.TypeBool,
			Optional:    true,
			Computed:    true,
			Description: "enable/disable account",
		},
		"resource_limits": {
			Type:     schema.TypeList,
			Optional: true,
			Computed: true,
			MaxItems: 1,
			Elem: &schema.Resource{
				Schema: map[string]*schema.Schema{
					"cu_c": {
						Type:     schema.TypeFloat,
						Optional: true,
						Computed: true,
					},
					"cu_d": {
						Type:     schema.TypeFloat,
						Optional: true,
						Computed: true,
					},
					"cu_dm": {
						Type:     schema.TypeFloat,
						Computed: true,
					},
					"cu_i": {
						Type:     schema.TypeFloat,
						Optional: true,
						Computed: true,
					},
					"cu_m": {
						Type:     schema.TypeFloat,
						Optional: true,
						Computed: true,
					},
					"gpu_units": {
						Type:     schema.TypeFloat,
						Optional: true,
						Computed: true,
					},
					"storage_policy": {
						Type:     schema.TypeList,
						Computed: true,
						Elem: &schema.Resource{
							Schema: map[string]*schema.Schema{
								"id": {
									Type:     schema.TypeInt,
									Computed: true,
								},
								"limit": {
									Type:     schema.TypeInt,
									Computed: true,
								},
							},
						},
					},
				},
			},
		},
		"account_id": {
			Type:     schema.TypeInt,
			Computed: true,
		},
		"dc_location": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"acl": {
			Type:     schema.TypeList,
			Computed: true,
			Elem: &schema.Resource{
				Schema: aclSchemaMake(),
			},
		},
		"company": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"companyurl": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"compute_features": {
			Type:     schema.TypeList,
			Computed: true,
			Elem: &schema.Schema{
				Type: schema.TypeString,
			},
		},
		"created_by": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"created_time": {
			Type:     schema.TypeInt,
			Computed: true,
		},
		"deactivation_time": {
			Type:     schema.TypeFloat,
			Computed: true,
		},
		"deleted_by": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"deleted_time": {
			Type:     schema.TypeInt,
			Computed: true,
		},
		"displayname": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"guid": {
			Type:     schema.TypeInt,
			Computed: true,
		},
		"status": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"updated_by": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"updated_time": {
			Type:     schema.TypeInt,
			Computed: true,
		},
		"version": {
			Type:     schema.TypeInt,
			Computed: true,
		},
		"vins": {
			Type:     schema.TypeList,
			Computed: true,
			Elem: &schema.Schema{
				Type: schema.TypeInt,
			},
		},
		"computes": {
			Type:     schema.TypeList,
			Computed: true,
			Elem: &schema.Resource{
				Schema: computesSchemaMake(),
			},
		},
		"machines": {
			Type:     schema.TypeList,
			Computed: true,
			Elem: &schema.Resource{
				Schema: machinesSchemaMake(),
			},
		},
		"vinses": {
			Type:     schema.TypeInt,
			Computed: true,
		},
		"cpu_allocation_parameter": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"cpu_allocation_ratio": {
			Type:     schema.TypeFloat,
			Computed: true,
		},
		"storage_policy_ids": {
			Type:     schema.TypeList,
			Computed: true,
			Elem: &schema.Schema{
				Type: schema.TypeInt,
			},
		},
	}
}

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