package disks

import (
	"context"
	"fmt"
	log "github.com/sirupsen/logrus"
	"strconv"
	"strings"

	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/disks"
	"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
)

func utilityDiskSnapshotCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (disks.ItemSnapshot, error) {
	log.Debugf("utilityDiskSnapshotCheckPresence: call for disk_id %d, label %s",
		d.Get("disk_id").(int),
		d.Get("label").(string))
	c := m.(*controller.ControllerCfg)

	req := disks.GetRequest{}
	snapshot := disks.ItemSnapshot{}

	if d.Id() != "" {
		arr := strings.Split(d.Id(), "#")
		if len(arr) != 2 {
			return snapshot, fmt.Errorf("broken state id")
		}
		req.DiskID, _ = strconv.ParseUint(arr[0], 10, 64)
	} else {
		req.DiskID = uint64(d.Get("disk_id").(int))
	}

	disk, err := c.CloudBroker().Disks().Get(ctx, req)
	if err != nil {
		return snapshot, err
	}

	snapshots := disk.Snapshots
	label := d.Get("label").(string)
	for _, sn := range snapshots {
		if label == sn.Label {
			snapshot = sn
			break
		}
	}
	if label != snapshot.Label {
		return snapshot, fmt.Errorf("snapshot with label \"%v\" not found", label)
	}

	return snapshot, nil
}
