package utilities

import (
	"context"
	"fmt"

	"github.com/hashicorp/terraform-plugin-framework/diag"
	"github.com/hashicorp/terraform-plugin-log/tflog"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/disks"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/client"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudbroker/disks/models"
)

func DataSourceDiskSnapshotCheckPresence(ctx context.Context, plan *models.DataSourceDiskSnapshotModel, c *client.Client) (*disks.ItemSnapshot, diag.Diagnostics) {
	diags := diag.Diagnostics{}

	diskId := uint64(plan.DiskID.ValueInt64())
	label := plan.Label.ValueString()
	tflog.Info(ctx, "Start DataSourceDiskSnapshotCheckPresence", map[string]any{"disk_id": diskId, "label": label})

	tflog.Info(ctx, "DataSourceDiskSnapshotCheckPresence: before call CloudBroker().Disks().Get", map[string]any{"disk_id": diskId})
	disk, err := c.CloudBroker().Disks().Get(ctx, disks.GetRequest{DiskID: diskId})
	if err != nil {
		diags.AddError(
			fmt.Sprintf("Cannot get info about disk with disk_id %d", diskId),
			err.Error(),
		)
		return nil, diags
	}
	tflog.Info(ctx, "DataSourceDiskSnapshotCheckPresence: response from CloudBroker().Disks().Get", map[string]any{"response": disk})

	for _, sn := range disk.Snapshots {
		if label == sn.Label {
			return &sn, nil
		}
	}

	diags.AddError(
		"Snapshot not found",
		fmt.Sprintf("Snapshot with label %s for disk with disk_id %d not found", label, diskId),
	)
	return nil, diags
}
