package lb

import (
	"context"

	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/extnet"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/lb"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/rg"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/vins"
	"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
)

func existLBID(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) {
	c := m.(*controller.ControllerCfg)
	lbId := uint64(d.Get("lb_id").(int))

	req := lb.ListRequest{}

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

	return len(lbList.FilterByID(lbId).Data) != 0, nil
}

func existRGID(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) {
	c := m.(*controller.ControllerCfg)
	rgId := uint64(d.Get("rg_id").(int))

	req := rg.ListRequest{}

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

	return len(rgList.FilterByID(rgId).Data) != 0, nil
}

func existExtNetID(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) {
	c := m.(*controller.ControllerCfg)
	extNetID := uint64(d.Get("extnet_id").(int))

	// this code is needed in order to be able to pass 0
	if extNetID == 0 {
		return true, nil
	}

	req := extnet.ListRequest{}

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

	return len(extNetList.FilterByID(extNetID).Data) != 0, nil
}

func existViNSID(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) {
	c := m.(*controller.ControllerCfg)
	vinsID := uint64(d.Get("vins_id").(int))

	// this code is needed in order to be able to pass 0
	if vinsID == 0 {
		return true, nil
	}

	req := vins.ListRequest{}

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

	return len(vinsList.FilterByID(vinsID).Data) != 0, nil
}
