/*
Copyright (c) 2019-2024 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 vfpool

import (
	"context"
	"fmt"
	"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/vfpool"
	"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"
)

func resourceVFPoolCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	vfpoolName := d.Get("name").(string)

	log.Debugf("resourceVFPoolCreate: called VFPool with name %s", vfpoolName)

	c := m.(*controller.ControllerCfg)

	req := vfpool.CreateRequest{
		Name: vfpoolName,
	}

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

	if accountAccess, ok := d.GetOk("account_access"); ok {
		accountAccessArray := accountAccess.(*schema.Set).List()

		req.AccountAccess = make([]uint64, 0, len(accountAccessArray))

		for _, access := range accountAccessArray {
			req.AccountAccess = append(req.AccountAccess, uint64(access.(int)))
		}
	}

	if rgAccess, ok := d.GetOk("rg_access"); ok {
		rgAccessArray := rgAccess.(*schema.Set).List()

		req.RGAccess = make([]uint64, 0, len(rgAccessArray))

		for _, access := range rgAccessArray {
			req.RGAccess = append(req.RGAccess, uint64(access.(int)))
		}
	}

	if err := checkParamsExistence(ctx, c, req.AccountAccess, req.RGAccess); err != nil {
		return err
	}

	config, configOk := d.GetOk("config")

	enableVal := d.Get("enable").(bool)
	if enableVal && !configOk {
		return diag.FromErr(fmt.Errorf("enable requires config to be set"))
	}

	if configOk {
		configArray := config.(*schema.Set).List()
		req.Config = make([]vfpool.Config, 0, len(configArray))

		for _, access := range configArray {
			temp := access.(map[string]interface{})

			vfArray := temp["vf_ids"].([]interface{})
			resVfIds := make([]uint64, 0, len(vfArray))

			for _, vfID := range vfArray {
				resVfIds = append(resVfIds, uint64(vfID.(int)))
			}

			reqTemp := vfpool.Config{
				NodeID:  uint64(temp["node_id"].(int)),
				NicName: temp["nic_name"].(string),
				VFIDs:   resVfIds,
			}
			req.Config = append(req.Config, reqTemp)
		}
	}

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

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

	warnings := dc.Warnings{}

	if err := utilityVFPoolEnabled(ctx, m, enableVal, vfPoolID); err != nil {
		warnings.Add(err)
	}

	log.Debugf("resourceVFPoolCreate: create VFPool with ID: %d, complete", vfPoolID)
	return append(resourceVFPoolRead(ctx, d, m), warnings.Get()...)
}

func resourceVFPoolRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	log.Debugf("resourceVFPoolRead: called VFPool with id %s", d.Id())

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

	flattenVFPoolResource(d, vfPool)

	log.Debugf("resourceVFPoolRead: read VFPool with id %s, complete", d.Id())
	return nil
}

func resourceVFPoolUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	vfPoolID, _ := strconv.ParseUint(d.Id(), 10, 64)

	log.Debugf("resourceVFPoolUpdate: called VFPool with id %d", vfPoolID)

	if d.HasChanges("name", "description", "account_access", "rg_access", "config", "enable") {
		if err := utilityVFPoolUpdate(ctx, d, m, vfPoolID); err != nil {
			return diag.FromErr(err)
		}
	}

	log.Debugf("resourceVFPoolUpdate: update VFPool with id %d, complete", vfPoolID)

	return resourceVFPoolRead(ctx, d, m)
}

func resourceVFPoolDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	log.Debugf("resourceVFPoolDelete: called VFPool with id %s", d.Id())

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

	c := m.(*controller.ControllerCfg)

	req := vfpool.DeleteRequest{
		VFPoolID: vfPool.ID,
	}

	if vfPool.Status == "ENABLED" || vfPool.Status == "CREATED" {
		reqDisable := vfpool.DisableRequest{
			VFPoolID: vfPool.ID,
		}

		log.Debugf("resourceVFPoolDelete: need to disable vfPool with ID: %d, after delete", vfPool.ID)
		_, err = c.CloudBroker().VFPool().Disable(ctx, reqDisable)
		if err != nil {
			return diag.FromErr(err)
		}
		log.Debugf("resourceVFPoolDelete: disable vfPool with ID: %d, complete", vfPool.ID)
	}

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

	d.SetId("")

	return nil
}

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

		CreateContext: resourceVFPoolCreate,
		ReadContext:   resourceVFPoolRead,
		UpdateContext: resourceVFPoolUpdate,
		DeleteContext: resourceVFPoolDelete,

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

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

		Schema: resourceVFPoolSchemaMake(),
	}
}
