package image

import (
	"context"
	"encoding/json"
	"net/http"
	"strconv"

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

// CreateCDROMImageRequest struct to create CD-ROM image
type CreateCDROMImageRequest struct {
	// Name of the rescue disk
	// Required: true
	Name string `url:"name" json:"name" validate:"required"`

	// URL where to download ISO from
	// Required: true
	URL string `url:"url" json:"url" validate:"required,url"`

	// ID of the chosen storage policy
	// Required: true
	StoragePolicyID uint64 `url:"storage_policy_id" json:"storage_policy_id" validate:"required"`

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

	// Storage endpoint provider ID for place rescue CD
	// Required: false
	SEPID uint64 `url:"sep_id,omitempty" json:"sep_id,omitempty"`

	// Pool for place rescue CD
	// Required: false
	PoolName string `url:"pool_name,omitempty" json:"pool_name,omitempty"`

	// Username for remote media download
	// Required: false
	UsernameDL string `url:"usernameDL,omitempty" json:"usernameDL,omitempty"`

	// Password for remote media download
	// Required: false
	PasswordDl string `url:"passwordDL,omitempty" json:"passwordDL,omitempty"`
}

type asyncWrapperCreateCDROMImageRequest struct {
	CreateCDROMImageRequest
	AsyncMode bool `url:"asyncMode"`
}

// CreateCDROMImage creates CD-ROM image from an ISO identified by URL
func (i Image) CreateCDROMImage(ctx context.Context, req CreateCDROMImageRequest) (uint64, error) {
	err := validators.ValidateRequest(req)
	if err != nil {
		return 0, validators.ValidationErrors(validators.GetErrors(err))
	}

	url := "/cloudbroker/image/createCDROMImage"

	syncReq := asyncWrapperCreateCDROMImageRequest{CreateCDROMImageRequest: req, AsyncMode: false}

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

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

	return result, nil
}

// AsyncCreateCDROMImage creates CD-ROM image from an ISO identified by URL in async mode
func (i Image) AsyncCreateCDROMImage(ctx context.Context, req CreateCDROMImageRequest) (string, error) {
	err := validators.ValidateRequest(req)
	if err != nil {
		return "", validators.ValidationErrors(validators.GetErrors(err))
	}

	url := "/cloudbroker/image/createCDROMImage"

	asyncReq := asyncWrapperCreateCDROMImageRequest{CreateCDROMImageRequest: req, AsyncMode: true}

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

	var taskID string

	err = json.Unmarshal(res, &taskID)
	if err != nil {
		return "", err
	}

	return taskID, nil
}
