/*
Copyright (c) 2019-2023 Digital Energy Cloud Solutions LLC. All Rights Reserved.
Authors:
Petr Krutov, <petr.krutov@digitalenergy.online>
Stanislav Solovev, <spsolovev@digitalenergy.online>
Sergey Kisil, <svkisil@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 sep

import (
	"context"
	"encoding/json"
	"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/sep"
	"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 resourceSepCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	log.Debugf("resourceSepCreate: called for sep %s", d.Get("name").(string))

	c := m.(*controller.ControllerCfg)

	if diags := checkParamsExistence(ctx, d, c); diags != nil {
		return diags
	}

	req := sep.CreateRequest{
		GID:     uint64(d.Get("gid").(int)),
		Name:    d.Get("name").(string),
		SEPType: d.Get("type").(string),
		Config:  d.Get("config").(string),
	}

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

	sepId, err := c.CloudBroker().SEP().Create(ctx, req)
	if err != nil {
		d.SetId("")
		return diag.FromErr(err)
	}

	d.SetId(strconv.FormatUint(sepId, 10))
	d.Set("sep_id", sepId)

	warnings := dc.Warnings{}

	if enable, ok := d.GetOk("enable"); ok {
		log.Debugf("resourceSepCreate, Enable: enable=%t sep_id %d after completing its resource configuration", enable, sepId)
		err := resourceSepChangeEnabled(ctx, d, m)
		if err != nil {
			warnings.Add(err)
		}
	}

	if accountIds, ok := d.GetOk("account_ids"); ok {
		log.Debugf("resourceSepCreate, accessGrant: accountIds=%v sep_id %d after completing its resource configuration", accountIds, sepId)
		err := resourceSepChangeAccess(ctx, d, m)
		if err != nil {
			warnings.Add(err)
		}
	}

	if accessToPool, ok := d.GetOk("access_to_pool"); ok {
		log.Debugf("resourceSepCreate, accessToPool: accessToPool=%v sep_id %d after completing its resource configuration", accessToPool, sepId)
		err := resourceSepChangeAccessToPool(ctx, d, m)
		if err != nil {
			warnings.Add(err)
		}
	}

	if pools, ok := d.GetOk("pools"); ok {
		log.Debugf("resourceSepCreate, pools: pools=%v sep_id %d after completing its resource configuration", pools, sepId)
		err := resourceSepChangePools(ctx, d, m)
		if err != nil {
			warnings.Add(err)
		}
	}

	if consumedBy, ok := d.GetOk("consumed_by"); ok && consumedBy.(*schema.Set).Len() > 0 {
		log.Debugf("resourceSepCreate, consumed_by: consumed_by=%v sep_id %d after completing its resource configuration", consumedBy, sepId)
		err := resourceSepAddConsumerNodes(ctx, d, m)
		if err != nil {
			warnings.Add(err)
		}
	}

	if providedBy, ok := d.GetOk("provided_by"); ok && len(providedBy.([]interface{})) > 0 {
		log.Debugf("resourceSepCreate, provided_by: provided_by=%v sep_id %d after completing its resource configuration", providedBy, sepId)
		err := resourceSepAddProviderNodes(ctx, d, m)
		if err != nil {
			warnings.Add(err)
		}
	}

	return append(resourceSepRead(ctx, d, m), warnings.Get()...)
}

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

	sepRec, err := utilitySepCheckPresence(ctx, d, m)
	if sepRec == nil {
		d.SetId("")
		return diag.FromErr(err)
	}

	flattenSep(d, sepRec)

	log.Debugf("resourceSepRead: after flattenSep: %s id: %d", d.Get("name").(string), d.Get("sep_id").(int))

	return nil
}

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

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

	c := m.(*controller.ControllerCfg)
	req := sep.DeleteRequest{
		SEPID: sepDes.ID,
	}

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

	d.SetId("")

	return nil
}

func resourceSepUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	return diag.Errorf(
		"SEP upgrade is not possible via terraform")

}

func resourceSepChangeAccess(ctx context.Context, d *schema.ResourceData, m interface{}) error {
	log.Debugf("resourceSepChangeAccess: called for %s, id: %d", d.Get("name").(string), d.Get("sep_id").(int))
	c := m.(*controller.ControllerCfg)

	oldSet, newSet := d.GetChange("account_ids")

	deletedAccounts := (oldSet.(*schema.Set).Difference(newSet.(*schema.Set))).List()
	var accountDelIds []uint64
	for _, deletedInterface := range deletedAccounts {
		deletedItem := deletedInterface.(int)
		accountDelIds = append(accountDelIds, uint64(deletedItem))
	}
	if len(accountDelIds) != 0 {
		for _, acc := range accountDelIds {
			reqDel := sep.AccessRevokeRequest{
				SEPID:     uint64(d.Get("sep_id").(int)),
				AccountID: acc,
			}
			_, err := c.CloudBroker().SEP().AccessRevoke(ctx, reqDel)
			if err != nil {
				return err
			}
		}
	}

	addedAccounts := (oldSet.(*schema.Set).Difference(newSet.(*schema.Set))).List()
	var accountAddIds []uint64
	for _, addedInterface := range addedAccounts {
		addedItem := addedInterface.(int)
		accountAddIds = append(accountAddIds, uint64(addedItem))
	}
	if len(accountAddIds) != 0 {
		for _, acc := range accountAddIds {
			reqDel := sep.AccessGrantRequest{
				SEPID:     uint64(d.Get("sep_id").(int)),
				AccountID: acc,
			}
			_, err := c.CloudBroker().SEP().AccessGrant(ctx, reqDel)
			if err != nil {
				return err
			}
		}
	}

	return nil
}

func resourceSepChangeAccessToPool(ctx context.Context, d *schema.ResourceData, m interface{}) error {
	log.Debugf("resourceSepChangeAccessToPool: called for %s, id: %d", d.Get("name").(string), d.Get("sep_id").(int))
	c := m.(*controller.ControllerCfg)

	oldAccessToPool, newAccessToPool := d.GetChange("access_to_pool")

	oldAccess := oldAccessToPool.([]interface{})[0].(map[string]interface{})
	if oldAccess["pool_name"] != "" {
		revokeReq := sep.AccessRevokeToPoolRequest{
			SEPID:    uint64(d.Get("sep_id").(int)),
			PoolName: oldAccess["pool_name"].(string),
		}

		if oldAccId, ok := oldAccess["account_id_pool"]; ok {
			revokeReq.AccountID = uint64(oldAccId.(int))
		}

		if oldRgId, ok := oldAccess["rg_id"]; ok {
			revokeReq.RGID = uint64(oldRgId.(int))
		}

		_, err := c.CloudBroker().SEP().AccessRevokeToPool(ctx, revokeReq)
		if err != nil {
			return err
		}
	}

	newAccess := newAccessToPool.([]interface{})[0].(map[string]interface{})
	if newAccess["pool_name"] != "" {
		grantReq := sep.AccessGrantToPoolRequest{
			SEPID:    uint64(d.Get("sep_id").(int)),
			PoolName: newAccess["pool_name"].(string),
		}

		if newAccId, ok := newAccess["account_id_pool"]; ok {
			grantReq.AccountID = uint64(newAccId.(int))
		}

		if newRgId, ok := newAccess["rg_id"]; ok {
			grantReq.RGID = uint64(newRgId.(int))
		}

		_, err := c.CloudBroker().SEP().AccessGrantToPool(ctx, grantReq)
		if err != nil {
			return err
		}
	}

	return nil
}

func resourceSepChangePools(ctx context.Context, d *schema.ResourceData, m interface{}) error {
	log.Debugf("resourceSepChangePools: called for %s, id: %d", d.Get("name").(string), d.Get("sep_id").(int))
	c := m.(*controller.ControllerCfg)

	oldPoolsInterface, newPoolsInterface := d.GetChange("pools")

	oldPoolsList := oldPoolsInterface.(*schema.Set).Difference(newPoolsInterface.(*schema.Set)).List()
	for _, pool := range oldPoolsList {
		delPoolReq := sep.DelPoolRequest{
			SEPID:    uint64(d.Get("sep_id").(int)),
			PoolName: pool.(string),
		}

		_, err := c.CloudBroker().SEP().DelPool(ctx, delPoolReq)
		if err != nil {
			return err
		}
	}

	newPoolsList := newPoolsInterface.(*schema.Set).Difference(oldPoolsInterface.(*schema.Set)).List()
	for _, pool := range newPoolsList {
		poolItem := pool.(map[string]interface{})

		accessAccountIDs := []uint64{}

		for _, v := range poolItem["access_account_ids"].([]interface{}) {
			accessAccountIDs = append(accessAccountIDs, uint64(v.(int)))
		}
		accessResGroupIDs := []uint64{}
		for _, v := range poolItem["access_res_group_ids"].([]interface{}) {
			accessResGroupIDs = append(accessResGroupIDs, uint64(v.(int)))
		}

		types := []string{}
		for _, v := range poolItem["types"].([]interface{}) {
			types = append(types, v.(string))
		}

		uris := []UrisModel{}
		list := poolItem["uris"].(*schema.Set).List()
		for _, v := range list {
			if m, ok := v.(map[string]interface{}); ok {
				uris = append(uris, UrisModel{IP: m["ip"].(string),
					Port: uint64(m["port"].(int)),
				})
			}
		}

		poolValue := PoolModel{
			AccessAccountIDs:  accessAccountIDs,
			AccessResGroupIDs: accessResGroupIDs,
			Name:              poolItem["name"].(string),
			Types:             types,
			Uris:              uris,
			UsageLimit:        uint64(poolItem["usage_limit"].(int)),
		}
		marshalPool, _ := json.Marshal(poolValue)
		log.Debugf(string(marshalPool))
		addPoolReq := sep.AddPoolRequest{
			SEPID: uint64(d.Get("sep_id").(int)),
			Pool:  string(marshalPool),
		}

		_, err := c.CloudBroker().SEP().AddPool(ctx, addPoolReq)
		if err != nil {
			return err
		}
	}

	return nil
}

func resourceSepUpdateConfig(ctx context.Context, d *schema.ResourceData, m interface{}) error {
	c := m.(*controller.ControllerCfg)

	validateReq := sep.ConfigValidateRequest{
		SEPID:  uint64(d.Get("sep_id").(int)),
		Config: d.Get("config").(string),
	}
	_, err := c.CloudBroker().SEP().ConfigValidate(ctx, validateReq)
	if err != nil {
		return err
	}

	insertReq := sep.ConfigInsertRequest{
		SEPID:  uint64(d.Get("sep_id").(int)),
		Config: d.Get("config").(string),
	}
	_, err = c.CloudBroker().SEP().ConfigInsert(ctx, insertReq)
	if err != nil {
		return err
	}

	return nil
}

func resourceSepFieldEdit(ctx context.Context, d *schema.ResourceData, m interface{}) error {
	c := m.(*controller.ControllerCfg)

	fieldConfig := d.Get("field_edit").([]interface{})
	field := fieldConfig[0].(map[string]interface{})
	req := sep.ConfigFieldEditRequest{
		SEPID:      uint64(d.Get("sep_id").(int)),
		FieldName:  field["field_name"].(string),
		FieldValue: field["field_value"].(string),
		FieldType:  field["field_type"].(string),
	}

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

	return nil
}

func resourceSepChangeEnabled(ctx context.Context, d *schema.ResourceData, m interface{}) error {
	c := m.(*controller.ControllerCfg)
	sepID := uint64(d.Get("sep_id").(int))

	if d.Get("enable").(bool) {
		req := sep.EnableRequest{
			SEPID: sepID,
		}

		_, err := c.CloudBroker().SEP().Enable(ctx, req)
		if err != nil {
			return err
		}
	} else {
		req := sep.DisableRequest{
			SEPID: sepID,
		}

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

	return nil
}

func resourceSepUpdateNodes(ctx context.Context, d *schema.ResourceData, m interface{}) error {
	log.Debugf("resourceSepUpdateNodes: called for %s, id: %d", d.Get("name").(string), d.Get("sep_id").(int))
	c := m.(*controller.ControllerCfg)

	oldSet, newSet := d.GetChange("consumed_by")

	deletedConsumed := (oldSet.(*schema.Set).Difference(newSet.(*schema.Set))).List()
	var consumerDelIds []uint64
	for _, deletedInterface := range deletedConsumed {
		deletedItem := deletedInterface.(int)
		consumerDelIds = append(consumerDelIds, uint64(deletedItem))
	}
	if len(consumerDelIds) != 0 {
		reqDel := sep.DelConsumerNodesRequest{
			SEPID:        uint64(d.Get("sep_id").(int)),
			ConsumerNIDs: consumerDelIds,
		}
		_, err := c.CloudBroker().SEP().DelConsumerNodes(ctx, reqDel)
		if err != nil {
			return err
		}
	}

	addedConsumed := (newSet.(*schema.Set).Difference(oldSet.(*schema.Set))).List()
	var consumerAddIds []uint64
	for _, addedInterface := range addedConsumed {
		AddedItem := addedInterface.(int)
		consumerAddIds = append(consumerAddIds, uint64(AddedItem))
	}
	if len(consumerAddIds) != 0 {
		reqAdd := sep.AddConsumerNodesRequest{
			SEPID:        uint64(d.Get("sep_id").(int)),
			ConsumerNIDs: consumerAddIds,
		}
		_, err := c.CloudBroker().SEP().AddConsumerNodes(ctx, reqAdd)
		if err != nil {
			return err
		}
	}
	return nil
}

func resourceSepUpdateProviders(ctx context.Context, d *schema.ResourceData, m interface{}) error {
	log.Debugf("resourceSepUpdateProviders: called for %s, id: %d", d.Get("name").(string), d.Get("sep_id").(int))
	c := m.(*controller.ControllerCfg)
	req := sep.AddProviderNodesRequest{
		SEPID: uint64(d.Get("sep_id").(int)),
	}

	var providerNIDs []uint64
	for _, item := range d.Get("provided_by").([]interface{}) {
		providerNIDs = append(providerNIDs, uint64(item.(int)))
	}
	req.ProviderNIDs = providerNIDs

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

	return nil
}

func resourceSepAddConsumerNodes(ctx context.Context, d *schema.ResourceData, m interface{}) error {
	log.Debugf("resourceSepAddConsumerNodes: called for %s, id: %d", d.Get("name").(string), d.Get("sep_id").(int))
	c := m.(*controller.ControllerCfg)

	var consumerNIDs []uint64
	for _, item := range d.Get("consumed_by").(*schema.Set).List() {
		consumerNIDs = append(consumerNIDs, uint64(item.(int)))
	}

	if len(consumerNIDs) > 0 {
		reqAdd := sep.AddConsumerNodesRequest{
			SEPID:        uint64(d.Get("sep_id").(int)),
			ConsumerNIDs: consumerNIDs,
		}
		_, err := c.CloudBroker().SEP().AddConsumerNodes(ctx, reqAdd)
		if err != nil {
			return err
		}
	}

	return nil
}

func resourceSepAddProviderNodes(ctx context.Context, d *schema.ResourceData, m interface{}) error {
	log.Debugf("resourceSepAddProviderNodes: called for %s, id: %d", d.Get("name").(string), d.Get("sep_id").(int))
	c := m.(*controller.ControllerCfg)

	var providerNIDs []uint64
	for _, item := range d.Get("provided_by").([]interface{}) {
		providerNIDs = append(providerNIDs, uint64(item.(int)))
	}

	if len(providerNIDs) > 0 {
		reqAdd := sep.AddProviderNodesRequest{
			SEPID:        uint64(d.Get("sep_id").(int)),
			ProviderNIDs: providerNIDs,
		}
		_, err := c.CloudBroker().SEP().AddProviderNodes(ctx, reqAdd)
		if err != nil {
			return err
		}
	}

	return nil
}

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

		CreateContext: resourceSepCreate,
		ReadContext:   resourceSepRead,
		UpdateContext: resourceSepUpdate,
		DeleteContext: resourceSepDelete,

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

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

		Schema: resourceSepSchemaMake(),
	}
}

type PoolModel struct {
	AccessAccountIDs  []uint64    `json:"accessAccountIds"`
	AccessResGroupIDs []uint64    `json:"accessResGroupIds"`
	Name              string      `json:"name"`
	Types             []string    `json:"types"`
	Uris              []UrisModel `json:"uris"`
	UsageLimit        uint64      `json:"usage_limit"`
}

type UrisModel struct {
	IP string `json:"ip"`

	Port uint64 `json:"port"`
}
