/*
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>
Tim Tkachev, <tvtkachev@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 flipgroup

import (
	"context"
	"fmt"

	"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/flipgroup"
	"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"

	log "github.com/sirupsen/logrus"
)

func resourceFlipgroupCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	log.Debugf("resourceFlipgroupCreate called with name: %s, accountID %v", d.Get("name").(string), d.Get("account_id").(int))

	c := m.(*controller.ControllerCfg)
	req := flipgroup.CreateRequest{
		AccountID:   uint64(d.Get("account_id").(int)),
		Name:        d.Get("name").(string),
		NetType:     d.Get("net_type").(string),
		NetID:       uint64(d.Get("net_id").(int)),
		IP:          d.Get("ip").(string),
		Description: d.Get("desc").(string),
	}

	resp, err := c.CloudAPI().FLIPGroup().Create(ctx, req)
	if err != nil {
		d.SetId("")
		return diag.FromErr(err)
	}

	d.SetId(fmt.Sprint(resp.ID))

	var warnings dc.Warnings

	if clientType, ok := d.GetOk("client_type"); ok {
		req.ClientType = clientType.(string)
	}

	if client_ids, ok := d.GetOk("client_ids"); ok {
		casted := client_ids.([]interface{})
		addComputesAfterCreation(ctx, &warnings, c, casted, resp.ID)
	}

	defer resourceFlipgroupRead(ctx, d, m)
	return warnings.Get()
}

func resourceFlipgroupRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	fg, err := utilityFlipgroupCheckPresence(ctx, d, m)
	if err != nil {
		d.SetId("")
		return diag.FromErr(err)
	}

	flattenFlipgroup(d, fg)

	return nil
}

func resourceFlipgroupUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	log.Debugf("resourceFlipgroupUpdate called with id: %v", d.Get("flipgroup_id").(int))
	c := m.(*controller.ControllerCfg)
	fg, err := utilityFlipgroupCheckPresence(ctx, d, m)
	if err != nil {
		d.SetId("")
		return diag.FromErr(err)
	}

	var warnings dc.Warnings
	basicUpdate := false
	req := flipgroup.EditRequest{FLIPGroupID: fg.ID}

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

	if d.HasChange("name") {
		req.Name = d.Get("name").(string)
		basicUpdate = true
	}

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

	if d.HasChange("client_ids") {
		handleClientIDsUpdate(ctx, d, c, fg, &warnings)
	}

	defer resourceFlipgroupRead(ctx, d, m)
	return warnings.Get()
}

func resourceFlipgroupDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	log.Debugf("resourceFlipgroupDelete called with id: %v", d.Get("flipgroup_id").(int))
	c := m.(*controller.ControllerCfg)

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

	req := flipgroup.DeleteRequest{
		FLIPGroupID: fg.ID,
	}

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

	d.SetId("")

	return nil
}

func resourceFlipgroupSchemaMake() map[string]*schema.Schema {
	return map[string]*schema.Schema{
		"account_id": {
			Type:        schema.TypeInt,
			Required:    true,
			Description: "Account ID",
		},
		"name": {
			Type:        schema.TypeString,
			Required:    true,
			Description: "Flipgroup name",
		},
		"net_id": {
			Type:        schema.TypeInt,
			Required:    true,
			Description: "EXTNET or ViNS ID",
		},
		"net_type": {
			Type:         schema.TypeString,
			Required:     true,
			ValidateFunc: validation.StringInSlice([]string{"EXTNET", "VINS"}, true),
			Description:  "Network type, EXTNET or VINS",
		},
		"client_type": {
			Type:         schema.TypeString,
			Optional:     true,
			Default:      "compute",
			Description:  "Type of client, 'compute' ('vins' will be later)",
			ValidateFunc: validation.StringInSlice([]string{"compute"}, true),
		},
		"ip": {
			Type:        schema.TypeString,
			Optional:    true,
			Computed:    true,
			Description: "IP address to associate with this group. If empty, the platform will autoselect IP address",
		},
		"desc": {
			Type:        schema.TypeString,
			Optional:    true,
			Computed:    true,
			Description: "Text description of this Flipgroup instance",
		},
		"client_ids": {
			Type:     schema.TypeList,
			Optional: true,
			Computed: true,
			Elem: &schema.Schema{
				Type: schema.TypeInt,
			},
			Description: "List of clients attached to this Flipgroup instance",
		},
		"flipgroup_id": {
			Type:     schema.TypeInt,
			Computed: true,
		},
		"account_name": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"conn_id": {
			Type:     schema.TypeInt,
			Computed: true,
		},
		"conn_type": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"created_by": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"created_time": {
			Type:     schema.TypeInt,
			Computed: true,
		},
		"default_gw": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"deleted_by": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"deleted_time": {
			Type:     schema.TypeInt,
			Computed: true,
		},
		"gid": {
			Type:     schema.TypeInt,
			Computed: true,
		},
		"guid": {
			Type:     schema.TypeInt,
			Computed: true,
		},
		"milestones": {
			Type:     schema.TypeInt,
			Computed: true,
		},
		"status": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"network": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"updated_by": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"updated_time": {
			Type:     schema.TypeInt,
			Computed: true,
		},
	}
}

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

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

		CreateContext: resourceFlipgroupCreate,
		ReadContext:   resourceFlipgroupRead,
		UpdateContext: resourceFlipgroupUpdate,
		DeleteContext: resourceFlipgroupDelete,

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

		Schema: resourceFlipgroupSchemaMake(),
	}
}
