package disks

import (
	"context"
	"net/http"
	"strconv"
	"strings"

	"repository.basistech.ru/BASIS/dynamix-golang-sdk/v14/internal/validators"
)

// FromPlatformDiskRequest struct to create template from platform disk
type FromPlatformDiskRequest struct {
	// ID of the disk
	// Required: true
	DiskID uint64 `url:"diskId" json:"diskId" validate:"required"`

	// Name of the rescue disk
	// Required: true
	Name string `url:"name" json:"name" validate:"required"`

	// Boot type of image BIOS or UEFI
	// Required: true
	BootType string `url:"boottype" json:"boottype" validate:"imageBootType"`

	// Image type linux, windows or other
	// Required: true
	ImageType string `url:"imagetype" json:"imagetype" validate:"imageType"`

	// Username for the image
	// Required: false
	Username string `url:"username,omitempty" json:"username,omitempty"`

	// Password for the image
	// Required: false
	Password string `url:"password,omitempty" json:"password,omitempty"`

	// Account ID to make the image exclusive
	// Required: false
	AccountID uint64 `url:"accountId,omitempty" json:"accountId,omitempty"`

	// Pool for image create
	// Required: false
	PoolName string `url:"poolName,omitempty" json:"poolName,omitempty"`

	// Does this machine supports hot resize
	// Required: false
	HotResize bool `url:"hotresize" json:"hotresize"`

	// Bootable image
	// Required: true
	Bootable bool `url:"bootable" json:"bootable"`
}

type wrapperFromPlatformDiskRequest struct {
	FromPlatformDiskRequest
	AsyncMode bool `url:"asyncMode"`
}

// FromPlatformDisk creates template from platform disk in sync mode.
// It returns id of created disk and error.
func (d Disks) FromPlatformDisk(ctx context.Context, req FromPlatformDiskRequest) (uint64, error) {
	err := validators.ValidateRequest(req)
	if err != nil {
		return 0, validators.ValidationErrors(validators.GetErrors(err))
	}

	url := "/cloudbroker/disks/fromPlatformDisk"

	reqWrapped := wrapperFromPlatformDiskRequest{
		FromPlatformDiskRequest: req,
		AsyncMode:               false,
	}

	res, err := d.client.DecortApiCall(ctx, http.MethodPost, url, reqWrapped)
	if err != nil {
		return 0, err
	}

	result, err := strconv.ParseUint(string(res), 10, 64)
	if err != nil {
		return 0, err
	}

	return result, nil
}

// FromPlatformDiskAsync creates template from platform disk in async mode.
// It returns guid of task and error.
func (d Disks) FromPlatformDiskAsync(ctx context.Context, req FromPlatformDiskRequest) (string, error) {
	err := validators.ValidateRequest(req)
	if err != nil {
		return "", validators.ValidationErrors(validators.GetErrors(err))
	}

	url := "/cloudbroker/disks/fromPlatformDisk"

	reqWrapped := wrapperFromPlatformDiskRequest{
		FromPlatformDiskRequest: req,
		AsyncMode:               true,
	}

	res, err := d.client.DecortApiCall(ctx, http.MethodPost, url, reqWrapped)
	if err != nil {
		return "", err
	}

	result := strings.ReplaceAll(string(res), "\"", "")

	return result, nil
}
