/*
Copyright (c) 2019-2023 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 extnet

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/extnet"
	"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"
	"repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudbroker/ic"
)

func resourceExtnetCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	log.Debugf("cloudbroker: resourceExtnetCreate called with name '%s'", d.Get("name").(string))
	c := m.(*controller.ControllerCfg)

	if err := ic.ExistGID(ctx, uint64(d.Get("gid").(int)), c); err != nil {
		return diag.FromErr(err)
	}
	if err := checkReserveIp(ctx, d, c); err != nil {
		return diag.FromErr(err)
	}

	req := extnet.CreateRequest{
		Name:   d.Get("name").(string),
		GID:    uint64(d.Get("gid").(int)),
		IPCIDR: d.Get("ipcidr").(string),
		VLANID: uint64(d.Get("vlan_id").(int)),
	}

	if gateway, ok := d.GetOk("gateway"); ok {
		req.Gateway = gateway.(string)
	}

	if dns, ok := d.GetOk("dns"); ok {
		res := make([]string, 0)
		for _, elem := range dns.([]interface{}) {
			res = append(res, elem.(string))
		}

		req.DNS = res
	}

	if ntp, ok := d.GetOk("ntp"); ok {
		res := make([]string, 0)
		for _, elem := range ntp.([]interface{}) {
			res = append(res, elem.(string))
		}

		req.NTP = res
	}

	if check_ips, ok := d.GetOk("check_ips"); ok {
		res := make([]string, 0)
		for _, elem := range check_ips.([]interface{}) {
			res = append(res, elem.(string))
		}

		req.CheckIPs = res
	}

	if virtual, ok := d.GetOk("virtual"); ok {
		req.Virtual = virtual.(bool)
	}

	if zoneID, ok := d.GetOk("zone_id"); ok {
		req.ZoneID = uint64(zoneID.(int))
	}

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

	if start_ip, ok := d.GetOk("start_ip"); ok {
		req.StartIP = start_ip.(string)
	}

	if end_ip, ok := d.GetOk("end_ip"); ok {
		req.EndIP = end_ip.(string)
	}

	if pre_reservations_num, ok := d.GetOk("pre_reservations_num"); ok {
		req.PreReservationsNum = uint64(pre_reservations_num.(int))
	}

	if ovs_bridge, ok := d.GetOk("ovs_bridge"); ok {
		req.OVSBridge = ovs_bridge.(string)
	}

	if highly_available, ok := d.GetOk("highly_available"); ok {
		req.HAMode = highly_available.(bool)
	}

	if sec_vnfdev_ip, ok := d.GetOk("sec_vnfdev_ip"); ok {
		req.SecVNFDevIP = sec_vnfdev_ip.(string)
	}

	if mtu, ok := d.GetOk("mtu"); ok {
		req.MTU = uint(mtu.(int))
	}

	req.EnableSecGroups = d.Get("enable_secgroups").(bool)

	log.Debugf("cloudbroker: Sent create request")
	netID, err := c.CloudBroker().ExtNet().Create(ctx, req)
	if err != nil {
		return diag.FromErr(err)
	}

	d.SetId(strconv.FormatUint(netID, 10))
	d.Set("extnet_id", netID)
	log.Debugf("cloudbroker: Extnet with id %d successfully created on platform", netID)

	var w dc.Warnings

	if d.Get("excluded_ips").(*schema.Set).Len() > 0 {
		ips := make([]string, 0)

		for _, ip := range d.Get("excluded_ips").(*schema.Set).List() {
			ips = append(ips, ip.(string))
		}

		req := extnet.IPsExcludeRequest{
			NetID: netID,
			IPs:   ips,
		}

		_, err := c.CloudBroker().ExtNet().IPsExclude(ctx, req)
		if err != nil {
			w.Add(err)
		}
	}

	if d.Get("shared_with").(*schema.Set).Len() > 0 {
		for _, id := range d.Get("shared_with").(*schema.Set).List() {
			req := extnet.AccessRemoveRequest{
				NetID:     uint64(d.Get("extnet_id").(int)),
				AccountID: uint64(id.(int)),
			}

			_, err := c.CloudBroker().ExtNet().AccessRemove(ctx, req)
			if err != nil {
				w.Add(err)
			}
		}
	}

	if d.Get("excluded_ips_range").(*schema.Set).Len() > 0 {
		for _, ip := range d.Get("excluded_ips_range").(*schema.Set).List() {
			req := extnet.IPsExcludeRangeRequest{
				NetID:   uint64(d.Get("extnet_id").(int)),
				IPStart: ip.(map[string]interface{})["ip_start"].(string),
				IPEnd:   ip.(map[string]interface{})["ip_end"].(string),
			}

			_, err := c.CloudBroker().ExtNet().IPsExcludeRange(ctx, req)
			if err != nil {
				w.Add(err)
			}
		}
	}

	if d.Get("enable").(bool) {
		log.Debugf("resourceExtnetCreate: trying to enable extnet with ID %d", netID)
		_, err := c.CloudBroker().ExtNet().Enable(ctx, extnet.EnableRequest{
			NetID: netID,
		})

		if err != nil {
			w.Add(err)
		}
	}

	// for reserve IP extnet must be enabled
	if d.Get("reserved_ip").(*schema.Set).Len() > 0 {
		for _, reservedIP := range d.Get("reserved_ip").(*schema.Set).List() {
			reservedIPMap := reservedIP.(map[string]interface{})
			req := extnet.AddReserveIPRequest{
				AccountID: uint64(reservedIPMap["account_id"].(int)),
				ExtNetID:  netID,
			}
			if ipCount, ok := reservedIPMap["ip_count"]; ok {
				req.IPCount = uint64(ipCount.(int))
			}
			if reservedIPMap["ips"].(*schema.Set).Len() > 0 {
				ips := reservedIPMap["ips"].(*schema.Set).List()
				for i, ip := range ips {
					if i >= int(req.IPCount) {
						break
					}
					req.IPs = append(req.IPs, ip.(string))
				}
			}

			_, err := c.CloudBroker().ExtNet().AddReserveIP(ctx, req)
			if err != nil {
				w.Add(err)
			}
		}
	}

	return resourceExtnetRead(ctx, d, m)
}

func resourceExtnetRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	log.Debugf("cloudbroker: resourceExtnetRead called with id %s", d.Id())
	recNet, err := utilityExtnetCheckPresence(ctx, d, m)
	if err != nil {
		d.SetId("")
		return diag.FromErr(err)
	}
	staticRouteList, err := utilityStaticRouteListInResourceCheckPresence(ctx, m, recNet.ID)
	if err != nil {
		return diag.FromErr(err)
	}

	flattenRecordExtnetResource(d, recNet, staticRouteList)

	return nil
}

func resourceExtnetUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	log.Debugf("cloudbroker: resourceExtnetUpdate called with id %s", d.Id())
	c := m.(*controller.ControllerCfg)

	if err := checkReserveIp(ctx, d, c); err != nil {
		return diag.FromErr(err)
	}

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

	if err := handleBasicUpdate(ctx, d, c, recNet); err != nil {
		return diag.FromErr(err)
	}

	if d.HasChange("enable") {
		if err := handleEnableUpdate(ctx, d, c, recNet); err != nil {
			return diag.FromErr(err)
		}
	}

	if d.HasChange("default_qos") {
		if err := handleDefaultQOSUpdate(ctx, d, c, recNet); err != nil {
			return diag.FromErr(err)
		}
	}

	if d.HasChange("dns") {
		if err := handleDNSUpdate(ctx, d, c, recNet); err != nil {
			return diag.FromErr(err)
		}
	}

	if d.HasChange("ntp") {
		if err := handleNTPUpdate(ctx, d, c, recNet); err != nil {
			return diag.FromErr(err)
		}
	}

	if d.HasChange("set_default") {
		if err := handleSetDefault(ctx, d, c, recNet); err != nil {
			return diag.FromErr(err)
		}
	}

	if d.HasChange("excluded_ips") {
		if err := handleExcludedIPsUpdate(ctx, d, c, recNet); err != nil {
			return diag.FromErr(err)
		}
	}

	if d.HasChange("excluded_ips_range") {
		if err := handleExcludedIPsRangeUpdate(ctx, d, c, recNet); err != nil {
			return diag.FromErr(err)
		}
	}

	if d.HasChange("reserved_ip") {
		if err := reservedIPsUpdate(ctx, d, c, recNet); err != nil {
			return diag.FromErr(err)
		}
	}

	if d.HasChange("shared_with") {
		if err := handleSharedWithUpdate(ctx, d, c); err != nil {
			return diag.FromErr(err)
		}
	}

	if d.HasChange("virtual") {
		if err := handleVirtualUpdate(ctx, d, c, recNet); err != nil {
			return diag.FromErr(err)
		}
	}

	if d.HasChange("restart") {
		if err := handleRestartUpdate(ctx, d, c, recNet); err != nil {
			return diag.FromErr(err)
		}
	}
	if d.HasChange("migrate") {
		if err := handleMigrateUpdate(ctx, d, c, recNet); err != nil {
			return diag.FromErr(err)
		}
	}

	if d.HasChange("zone_id") {
		if err := handleZoneIDUpdate(ctx, d, c, recNet); err != nil {
			return diag.FromErr(err)
		}
	}

	if d.HasChange("highly_available") {
		if err := handleHAUpdate(ctx, d, c, recNet); err != nil {
			return diag.FromErr(err)
		}
	}

	return resourceExtnetRead(ctx, d, m)
}

func resourceExtnetDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	log.Debugf("cloudbroker: resourceExtnetDelete called with id %s", d.Id())
	c := m.(*controller.ControllerCfg)

	netId, _ := strconv.ParseUint(d.Id(), 10, 64)
	req := extnet.DestroyRequest{NetID: netId}

	_, err := c.CloudBroker().ExtNet().Destroy(ctx, req)
	if err != nil {
		return diag.FromErr(err)
	}
	log.Debugf("cloudbroker: successfully destroyed extnet with id %s", d.Id())

	return nil
}

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

		ReadContext:   resourceExtnetRead,
		CreateContext: resourceExtnetCreate,
		UpdateContext: resourceExtnetUpdate,
		DeleteContext: resourceExtnetDelete,

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

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

		CustomizeDiff: validateReserveIPs,

		Schema: resourceExtnetSchemaMake(),
	}
}
