package client

import (
	"context"
	"fmt"

	"errors"

	decortsdk "repository.basistech.ru/BASIS/decort-golang-sdk"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/compute"
)

type Migrator interface {
	Migrate(ctxOrigin context.Context, vmUUID, to uint64) (bool, error)
}

type migrator struct {
	cfg    *Config
	client decortsdk.ClientInterface
}

func NewMigrator(cfg *Config, c decortsdk.ClientInterface) Migrator {
	return &migrator{
		cfg:    cfg,
		client: c,
	}
}

func (m *migrator) Migrate(ctxOrigin context.Context, dxVMID, nodeID uint64) (bool, error) {
	req := compute.MigrateRequest{
		ComputeID:    dxVMID,
		TargetNodeID: nodeID,
	}
	ctx, cancel := context.WithTimeout(ctxOrigin, m.cfg.QueryTimeout)
	ok, err := m.client.CloudBroker().Compute().Migrate(ctx, req)
	cancel()
	if err != nil {
		return false, errors.Join(err, fmt.Errorf("Migrate VM %d to Node %d", dxVMID, nodeID))
	}
	return ok, nil
}
