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

import (
	"context"
	"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/zone"
	"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 resourceZoneCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	zoneName := d.Get("name").(string)

	log.Debugf("resourceZoneCreate: called Zone with name %s", zoneName)

	c := m.(*controller.ControllerCfg)

	req := zone.CreateRequest{
		Name: zoneName,
	}

	if aS, ok := d.GetOk("auto_start"); ok {
		req.AutoStart = aS.(bool)
	}

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

	if drs, ok := d.GetOkExists("drs"); ok {
		req.DRS = drs.(bool)
	}

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

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

	warnings := dc.Warnings{}

	if nodeIDs, ok := d.GetOk("node_ids"); ok {
		nodeIDsArr := nodeIDs.([]interface{})
		if len(nodeIDsArr) > 0 {

			addedUint := make([]uint64, len(nodeIDsArr))
			for i, v := range nodeIDsArr {
				addedUint[i] = uint64(v.(int))
			}

			req := zone.AddNodeRequest{
				ID:      zoneID,
				NodeIDs: addedUint,
			}
			if _, err := c.CloudBroker().Zone().AddNode(ctx, req); err != nil {
				warnings.Add(err)
			}

		}
	}

	log.Debugf("resourceZoneCreate: create Zone with ID: %d, complete", zoneID)
	return append(resourceZoneRead(ctx, d, m), warnings.Get()...)
}

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

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

	flattenZone(d, zone)

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

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

	log.Debugf("resourceZoneUpdate: called Zone with id %d", zoneID)

	if d.HasChanges("name", "description", "node_ids", "auto_start") {
		if err := utilityZoneUpdate(ctx, d, m, zoneID); err != nil {
			return diag.FromErr(err)
		}
	}

	log.Debugf("resourceZoneUpdate: update Zone with id %d, complete", zoneID)

	return resourceZoneRead(ctx, d, m)
}

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

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

	c := m.(*controller.ControllerCfg)

	req := zone.DeleteRequest{
		ID: zoneItem.ID,
	}

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

	d.SetId("")

	return nil
}

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

		CreateContext: resourceZoneCreate,
		ReadContext:   resourceZoneRead,
		UpdateContext: resourceZoneUpdate,
		DeleteContext: resourceZoneDelete,

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

func resourceZoneSchemaMake() map[string]*schema.Schema {
	return map[string]*schema.Schema{
		"name": {
			Type:     schema.TypeString,
			Required: true,
		},
		"description": {
			Type:     schema.TypeString,
			Optional: true,
			Computed: true,
		},
		"node_ids": {
			Type:     schema.TypeList,
			Optional: true,
			Computed: true,
			Elem: &schema.Schema{
				Type: schema.TypeInt,
			},
		},
		"auto_start": {
			Type:     schema.TypeBool,
			Optional: true,
			Default:  false,
		},
		"drs": {
			Type:     schema.TypeBool,
			Optional: true,
			Computed: true,
		},
		"drs_uid": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"drs_name": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"sso_url": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"app_id": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"decort_url": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"domain": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"ping_addr": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"broadcast_addr": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"ssl_skip_verify": {
			Type:     schema.TypeBool,
			Computed: true,
		},
		"sso_type": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"zone_id": {
			Type:     schema.TypeInt,
			Computed: true,
		},
		"guid": {
			Type:     schema.TypeInt,
			Computed: true,
		},
		"gid": {
			Type:     schema.TypeInt,
			Computed: true,
		},
		"deletable": {
			Type:     schema.TypeBool,
			Computed: true,
		},
		"status": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"created_time": {
			Type:     schema.TypeInt,
			Computed: true,
		},
		"updated_time": {
			Type:     schema.TypeInt,
			Computed: true,
		},
		"id": {
			Type:     schema.TypeString,
			Computed: true,
		},
	}
}
