package trunk

import (
	"context"
	"strconv"

	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
	log "github.com/sirupsen/logrus"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/trunk"
	"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
)

func utilityTrunkCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*trunk.ItemTrunk, error) {
	c := m.(*controller.ControllerCfg)
	req := trunk.GetRequest{}

	if d.Get("trunk_id") != nil {
		if d.Get("trunk_id").(int) == 0 {
			id, err := strconv.ParseUint(d.Id(), 10, 64)
			if err != nil {
				return nil, err
			}

			req.TrunkID = id
		} else {
			req.TrunkID = uint64(d.Get("trunk_id").(int))
		}
	} else {
		id, err := strconv.ParseUint(d.Id(), 10, 64)
		if err != nil {
			return nil, err
		}

		req.TrunkID = id
	}

	log.Debugf("utilityTrunkCheckPresence: get trunk network")

	trunkItem, err := c.CloudAPI().Trunk().Get(ctx, req)
	if err != nil {
		return nil, err
	}

	return trunkItem, nil
}
