// Input checks
package ic

import (
	"context"
	"fmt"

	cb_account "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/account"
	cb_compute "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/compute"
	cb_disks "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/disks"
	cb_dpdk "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/dpdknet"
	cb_extnet "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/extnet"
	cb_gid "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/grid"
	cb_image "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/image"
	cb_k8ci "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/k8ci"
	cb_k8s "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/k8s"
	cb_lb "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/lb"
	cb_node "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/node"
	cb_rg "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/rg"
	cb_trunk "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/trunk"
	cb_vfpool "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/vfpool"
	cb_vins "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/vins"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/sdn/logicalports"

	"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
)

func ExistRG(ctx context.Context, rgId uint64, c *controller.ControllerCfg) error {
	req := cb_rg.ListRequest{
		ByID:           rgId,
		IncludeDeleted: false,
	}

	rgList, err := c.CloudBroker().RG().List(ctx, req)
	if err != nil {
		return err
	}

	if len(rgList.Data) == 0 {
		return fmt.Errorf("RG with id %v not found", rgId)
	}

	return nil
}

func ExistRGs(ctx context.Context, rgIDs []uint64, c *controller.ControllerCfg) error {
	req := cb_rg.ListRequest{}

	rgList, err := c.CloudBroker().RG().List(ctx, req)
	if err != nil {
		return err
	}

	if len(rgList.Data) == 0 {
		return fmt.Errorf("you have not been granted access to any resource group")
	}

	notFound := make([]uint64, 0, len(rgIDs))

	for _, rgID := range rgIDs {
		found := false

		for _, rg := range rgList.Data {
			if rgID == rg.ID {
				found = true
				break
			}
		}

		if !found {
			notFound = append(notFound, rgID)
		}
	}

	if len(notFound) > 0 {
		return fmt.Errorf("RGs with ids %v not found", notFound)
	}

	return nil
}

func ExistAccouts(ctx context.Context, accountIDs []uint64, c *controller.ControllerCfg) error {
	req := cb_account.ListRequest{}

	accList, err := c.CloudBroker().Account().List(ctx, req)
	if err != nil {
		return err
	}

	if len(accList.Data) == 0 {
		return fmt.Errorf("you have not been granted access to any account")
	}

	notFound := make([]uint64, 0, len(accountIDs))

	for _, accID := range accountIDs {
		found := false

		for _, acc := range accList.Data {
			if accID == acc.ID {
				found = true
				break
			}
		}

		if !found {
			notFound = append(notFound, accID)
		}
	}

	if len(notFound) > 0 {
		return fmt.Errorf("Accounts with ids %v not found", notFound)
	}

	return nil
}

func ExistImage(ctx context.Context, imageId uint64, c *controller.ControllerCfg) error {
	req := cb_image.ListRequest{
		ByID: imageId,
	}

	listImages, err := c.CloudBroker().Image().List(ctx, req)
	if err != nil {
		return err
	}

	if len(listImages.Data) == 0 {
		return fmt.Errorf("image with id %v not found", imageId)
	}

	return nil
}

func ExistImages(ctx context.Context, imageIDs []uint64, c *controller.ControllerCfg) error {
	req := cb_image.ListRequest{}

	listImages, err := c.CloudBroker().Image().List(ctx, req)
	if err != nil {
		return err
	}

	if len(listImages.Data) == 0 {
		return fmt.Errorf("you have not been granted access to any images")
	}

	notFound := make([]uint64, 0, len(imageIDs))

	for _, imageID := range imageIDs {
		found := false

		for _, image := range listImages.Data {
			if imageID == image.ID {
				found = true
				break
			}
		}

		if !found {
			notFound = append(notFound, imageID)
		}
	}

	if len(notFound) > 0 {
		return fmt.Errorf("images with ids %v not found", notFound)
	}

	return nil
}

func ExistVins(ctx context.Context, vinsId uint64, c *controller.ControllerCfg) error {
	req := cb_vins.ListRequest{
		ByID:           vinsId,
		IncludeDeleted: false,
	}

	vinsList, err := c.CloudBroker().VINS().List(ctx, req)
	if err != nil {
		return err
	}

	if len(vinsList.Data) == 0 {
		return fmt.Errorf("vins with ID %v not found", vinsId)
	}

	return nil
}

func ExistVinses(ctx context.Context, vinsIds []uint64, c *controller.ControllerCfg) []error {
	var errs []error

	if len(vinsIds) == 0 {
		return errs
	}

	req := cb_vins.ListRequest{
		IncludeDeleted: false,
	}

	vinsList, err := c.CloudBroker().VINS().List(ctx, req)
	if err != nil {
		errs = append(errs, err)
		return errs
	}

	for _, vinsId := range vinsIds {
		found := false

		for _, vins := range vinsList.Data {
			if vinsId == vins.ID {
				found = true
				break
			}
		}

		if !found {
			errs = append(errs, fmt.Errorf("VINS with ID %v not found", vinsId))
		}
	}

	return errs
}

func ExistExtNets(ctx context.Context, extNetIds []uint64, c *controller.ControllerCfg) []error {
	var errs []error

	if len(extNetIds) == 0 {
		return errs
	}

	req := cb_extnet.ListRequest{}

	extNetList, err := c.CloudBroker().ExtNet().List(ctx, req)
	if err != nil {
		errs = append(errs, err)
		return errs
	}

	for _, extNetId := range extNetIds {
		found := false

		for _, extNet := range extNetList.Data {
			if extNetId == extNet.ID {
				found = true
				break
			}
		}

		if !found {
			errs = append(errs, fmt.Errorf("EXTNET with ID %v not found", extNetId))
		}
	}

	return errs
}

func ExistVFPools(ctx context.Context, vfpoolIds []uint64, c *controller.ControllerCfg) []error {
	var errs []error

	if len(vfpoolIds) == 0 {
		return errs
	}

	req := cb_vfpool.ListRequest{}

	vfpoolList, err := c.CloudBroker().VFPool().List(ctx, req)
	if err != nil {
		errs = append(errs, err)
		return errs
	}

	for _, vfpoolId := range vfpoolIds {
		found := false

		for _, vfpool := range vfpoolList.Data {
			if vfpoolId == vfpool.ID {
				found = true
				break
			}
		}

		if !found {
			errs = append(errs, fmt.Errorf("VFPool with ID %v not found", vfpoolId))
		}
	}

	return errs
}

func ExistDPDKNet(ctx context.Context, dpdkIds []uint64, c *controller.ControllerCfg) []error {
	var errs []error

	if len(dpdkIds) == 0 {
		return errs
	}

	req := cb_dpdk.ListRequest{}

	dpdkList, err := c.CloudBroker().DPDKNet().List(ctx, req)
	if err != nil {
		errs = append(errs, err)
		return errs
	}

	for _, dpdkId := range dpdkIds {
		found := false

		for _, dpdk := range dpdkList.Data {
			if dpdkId == dpdk.ID {
				found = true
				break
			}
		}

		if !found {
			errs = append(errs, fmt.Errorf("DPDKNet with ID %v not found", dpdkId))
		}
	}

	return errs
}

func ExistTrunkNet(ctx context.Context, trunkIds []uint64, c *controller.ControllerCfg) []error {
	var errs []error

	if len(trunkIds) == 0 {
		return errs
	}

	req := cb_trunk.ListRequest{}

	trunkList, err := c.CloudBroker().Trunk().List(ctx, req)
	if err != nil {
		errs = append(errs, err)
		return errs
	}

	for _, trunkId := range trunkIds {
		found := false

		for _, trunk := range trunkList.Data {
			if trunkId == trunk.ID {
				found = true
				break
			}
		}

		if !found {
			errs = append(errs, fmt.Errorf("TRUNK Net with ID %v not found", trunkId))
		}
	}

	return errs
}

func ExistExtNetInLb(ctx context.Context, extNetId uint64, c *controller.ControllerCfg) error {
	if extNetId == 0 {
		return nil
	}
	req := cb_extnet.ListRequest{
		ByID: extNetId,
	}

	extNetList, err := c.CloudBroker().ExtNet().List(ctx, req)
	if err != nil {
		return err
	}

	if len(extNetList.Data) == 0 {
		return fmt.Errorf("EXTNET with ID %v not found", extNetId)
	}

	return nil
}

func ExistExtNetInRG(ctx context.Context, extNetId, accountId uint64, c *controller.ControllerCfg) error {
	req := cb_extnet.ListRequest{
		AccountID: accountId,
		ByID:      extNetId,
	}

	listExtNet, err := c.CloudBroker().ExtNet().List(ctx, req)
	if err != nil {
		return err
	}

	if len(listExtNet.Data) == 0 {
		return fmt.Errorf("EXTNET with ID %v not found for account with id %d", extNetId, accountId)
	}

	return nil
}

func ExistExtNetInVins(ctx context.Context, extNetId int, c *controller.ControllerCfg) error {
	if extNetId == 0 || extNetId == -1 {
		return nil
	}
	req := cb_extnet.ListRequest{
		ByID: uint64(extNetId),
	}

	extNetList, err := c.CloudBroker().ExtNet().List(ctx, req)
	if err != nil {
		return err
	}

	if len(extNetList.Data) == 0 {
		return fmt.Errorf("EXTNET with ID %v not found", extNetId)
	}

	return nil
}

func ExistExtNet(ctx context.Context, extNetId uint64, c *controller.ControllerCfg) error {

	req := cb_extnet.ListRequest{
		ByID:   extNetId,
		Status: "Enabled",
	}

	extNetList, err := c.CloudBroker().ExtNet().List(ctx, req)
	if err != nil {
		return err
	}

	if len(extNetList.Data) == 0 {
		return fmt.Errorf("EXTNET with ID %v not found", extNetId)
	}

	return nil
}

func ExistVinsInLb(ctx context.Context, vinsId uint64, c *controller.ControllerCfg) error {
	if vinsId == 0 {
		return nil
	}

	req := cb_vins.ListRequest{
		ByID: vinsId,
	}

	vinsList, err := c.CloudBroker().VINS().List(ctx, req)
	if err != nil {
		return err
	}

	if len(vinsList.Data) == 0 {
		return fmt.Errorf("VINS with ID %v not found", vinsId)
	}

	return nil
}

func ExistGID(ctx context.Context, gid uint64, c *controller.ControllerCfg) error {
	req := cb_gid.ListRequest{}

	gridList, err := c.CloudBroker().Grid().List(ctx, req)
	if err != nil {
		return err
	}

	for _, grid := range gridList.Data {
		if grid.GID == gid {
			return nil
		}
	}

	return fmt.Errorf("GID with id %v not found", gid)
}

func ExistNode(ctx context.Context, nodeId uint64, c *controller.ControllerCfg) error {
	req := cb_node.ListRequest{
		ByID: nodeId,
	}

	nodeList, err := c.CloudBroker().Node().List(ctx, req)
	if err != nil {
		return err
	}

	if len(nodeList.Data) == 0 {
		return fmt.Errorf("node with id %v not found", nodeList)
	}

	return nil
}

func ExistLB(ctx context.Context, lbId uint64, c *controller.ControllerCfg) error {

	req := cb_lb.ListRequest{
		ByID: lbId,
	}

	lbList, err := c.CloudBroker().LB().List(ctx, req)
	if err != nil {
		return err
	}

	if len(lbList.Data) == 0 {
		return fmt.Errorf("LB with ID %v not found", lbId)
	}

	return nil

}

func ExistAccount(ctx context.Context, accountId uint64, c *controller.ControllerCfg) error {
	req := cb_account.ListRequest{
		ByID: accountId,
	}

	accountList, err := c.CloudBroker().Account().List(ctx, req)
	if err != nil {
		return err
	}

	if len(accountList.Data) == 0 {
		return fmt.Errorf("account with id %d not found", accountId)
	}

	return nil
}

func ExistK8CI(ctx context.Context, k8ciId uint64, c *controller.ControllerCfg) error {
	req := cb_k8ci.ListRequest{
		ByID: k8ciId,
	}

	k8ciList, err := c.CloudBroker().K8CI().List(ctx, req)
	if err != nil {
		return err
	}

	if len(k8ciList.Data) == 0 {
		return fmt.Errorf("k8ci with id %d not found", k8ciId)
	}

	return nil
}

func ExistExtNetInK8s(ctx context.Context, extNetId uint64, c *controller.ControllerCfg) error {
	if extNetId == 0 {
		return nil
	}
	req := cb_extnet.ListRequest{
		ByID: extNetId,
	}

	extNetList, err := c.CloudBroker().ExtNet().List(ctx, req)
	if err != nil {
		return err
	}

	if len(extNetList.Data) == 0 {
		return fmt.Errorf("EXTNET with ID %v not found", extNetId)
	}

	return nil
}

func ExistVinsInK8s(ctx context.Context, vinsId uint64, c *controller.ControllerCfg) error {
	if vinsId == 0 {
		return nil
	}

	req := cb_vins.ListRequest{
		ByID: vinsId,
	}

	vinsList, err := c.CloudBroker().VINS().List(ctx, req)
	if err != nil {
		return err
	}

	if len(vinsList.Data) == 0 {
		return fmt.Errorf("VINS with ID %v not found", vinsId)
	}

	return nil
}

func ExistK8s(ctx context.Context, k8sId uint64, c *controller.ControllerCfg) error {
	req := cb_k8s.ListRequest{
		ByID: k8sId,
	}

	k8sList, err := c.CloudBroker().K8S().List(ctx, req)
	if err != nil {
		return err
	}

	if len(k8sList.Data) == 0 {
		return fmt.Errorf("k8s with id %d not found", k8sId)
	}

	return nil
}

func IsMoreThanOneDisksTypeB(ctx context.Context, disks interface{}, chipset string) error {
	count := 0

	key := "bus_number"
	if chipset == "i440fx" {
		key = "pci_slot"
	}

	for _, elem := range disks.([]interface{}) {
		diskVal := elem.(map[string]interface{})

		if val, ok := diskVal[key].(int); ok && val == 6 {
			count++
		}

		if count > 1 {
			return fmt.Errorf("block disks have more 1 disk type 'B'")
		}
	}

	return nil
}

func ExistDiskID(ctx context.Context, diskId uint64, m interface{}) error {
	c := m.(*controller.ControllerCfg)

	req := cb_disks.ListRequest{
		ByID: diskId,
	}

	diskList, err := c.CloudBroker().Disks().List(ctx, req)
	if err != nil {
		return err
	}

	if len(diskList.Data) == 0 {
		return fmt.Errorf("resourceDiskReplication: can't create or update Disk replication because DiskID %d is not allowed or does not exist", diskId)
	}

	if diskList.Data[0].SEPType != "TATLIN" {
		return fmt.Errorf("resourceDiskReplication: can't create or update Disk replication because DiskID %d is not TATLIN SEP Type", diskId)
	}

	return nil
}

func ExistBlankCompute(ctx context.Context, computeId uint64, m interface{}) error {
	c := m.(*controller.ControllerCfg)
	req := cb_compute.GetRequest{ComputeID: computeId}

	// check for compute existence
	computeRecord, err := c.CloudBroker().Compute().Get(ctx, req)
	if err != nil {
		return fmt.Errorf("ComputeID %d is not allowed or does not exist", computeId)
	}

	// check if compute was created as blank
	computeImageId := computeRecord.ImageID
	bootImageId := -1
	for _, d := range computeRecord.Disks {
		if computeRecord.Chipset == "i440fx" {
			if d.PCISlot == 6 {
				bootImageId = int(d.ImageID)
				break
			}
		} else {
			if d.BusNumber == 6 {
				bootImageId = int(d.ImageID)
				break
			}
		}
	}

	if computeImageId != 0 && bootImageId != 0 {
		return fmt.Errorf("ComputeID %d is not allowed because it is not blank compute (either compute imageId or boot imageId are not zero)", computeId)
	}

	return nil
}

func ExistPlatformDisk(ctx context.Context, diskId uint64, m interface{}) error {
	c := m.(*controller.ControllerCfg)

	req := cb_disks.ListRequest{
		ByID: diskId,
	}

	diskList, err := c.CloudBroker().Disks().List(ctx, req)
	if err != nil {
		return err
	}

	if len(diskList.Data) != 1 {
		return fmt.Errorf("DiskID %d is not allowed or does not exist", diskId)
	}

	return nil
}

func ExistSDNNet(ctx context.Context, sdnIds []string, c *controller.ControllerCfg) []error {
	var errs []error

	for _, uniqueIdentifier := range sdnIds {
		if uniqueIdentifier == "" {
			continue
		}
		req := logicalports.GetByUniqueIdentifierRequest{ID: uniqueIdentifier}
		_, err := c.SDN().LogicalPorts().GetByUniqueIdentifier(ctx, req)
		if err != nil {
			errs = append(errs, fmt.Errorf("SDN logical port with unique identifier %q not found", uniqueIdentifier))
		}
	}

	return errs
}
