package kvmvm

import (
	"context"

	"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
	"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 checkParamsExistence(ctx context.Context, d *schema.ResourceData, c *controller.ControllerCfg) diag.Diagnostics {
	errs := []error{}

	if err := ic.ExistRG(ctx, uint64(d.Get("rg_id").(int)), c); err != nil {
		errs = append(errs, err)
	}

	if !d.Get("create_blank").(bool) {
		if err := ic.ExistImage(ctx, uint64(d.Get("image_id").(int)), c); err != nil {
			errs = append(errs, err)
		}
	}

	if netErrs := existNetworks(ctx, d, c); errs != nil {
		errs = append(errs, netErrs...)
	}

	if disks, ok := d.GetOk("disks"); ok {
		if err := ic.IsMoreThanOneDisksTypeB(ctx, disks, d.Get("chipset").(string)); err != nil {
			errs = append(errs, err)
		}
	}

	return dc.ErrorsToDiagnostics(errs)
}

func existNetworks(ctx context.Context, d *schema.ResourceData, c *controller.ControllerCfg) []error {
	var errs []error
	var vinsIds, extNetIds, vfpoolIds, dpdkIds, trunkIds []uint64
	var sdnIds []string

	networksIface, ok := d.GetOk("network")
	if !ok {
		return nil
	}

	networkList := networksIface.(*schema.Set).List()
	for _, elem := range networkList {
		network := elem.(map[string]interface{})

		switch network["net_type"].(string) {
		case "VINS":
			vinsIds = append(vinsIds, uint64(network["net_id"].(int)))
		case "EXTNET":
			extNetIds = append(extNetIds, uint64(network["net_id"].(int)))
		case "VFNIC":
			vfpoolIds = append(vfpoolIds, uint64(network["net_id"].(int)))
		case "DPDK":
			dpdkIds = append(dpdkIds, uint64(network["net_id"].(int)))
		case "TRUNK":
			trunkIds = append(trunkIds, uint64(network["net_id"].(int)))
		case "SDN":
			sdnIds = append(sdnIds, network["sdn_interface_id"].(string))
		default:
			continue
		}
	}

	if vinsErrs := ic.ExistVinses(ctx, vinsIds, c); vinsErrs != nil {
		errs = append(errs, vinsErrs...)
	}

	if extNetErrs := ic.ExistExtNets(ctx, extNetIds, c); extNetErrs != nil {
		errs = append(errs, extNetErrs...)
	}

	if vfpoolErrs := ic.ExistVFPools(ctx, vfpoolIds, c); vfpoolErrs != nil {
		errs = append(errs, vfpoolErrs...)
	}

	if dpdkErrs := ic.ExistDPDKNet(ctx, dpdkIds, c); dpdkErrs != nil {
		errs = append(errs, dpdkErrs...)
	}

	if trunkErrs := ic.ExistTrunkNet(ctx, trunkIds, c); trunkErrs != nil {
		errs = append(errs, trunkErrs...)
	}

	if sdnErrs := ic.ExistSDNNet(ctx, sdnIds, c); sdnErrs != nil {
		errs = append(errs, sdnErrs...)
	}

	return errs
}
