package lb

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

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

// UpdateSysctParamsRequest struct to update sysct params for lb
type UpdateSysctParamsRequest struct {
	// ID of the LB instance
	// Required: true
	LBID uint64 `url:"lbId" json:"lbId" validate:"required"`

	// Custom sysctl values for Load Balancer instance. Applied on boot
	// Required: true
	SysctlParams []map[string]interface{} `url:"-" json:"sysctlParams" validate:"required,dive"`
}

type wrapperUpdateSysctParamsRequest struct {
	UpdateSysctParamsRequest
	Params []string `url:"sysctlParams" validate:"required"`
}

// UpdateSysctParams updates sysct paarams for lb
func (l LB) UpdateSysctlParams(ctx context.Context, req UpdateSysctParamsRequest) (bool, error) {
	err := validators.ValidateRequest(req)
	if err != nil {
		return false, validators.ValidationErrors(validators.GetErrors(err))
	}

	var params []string

	if len(req.SysctlParams) != 0 {
		params = make([]string, 0, len(req.SysctlParams))
		for _, m := range req.SysctlParams {
			encodeStr, err := json.Marshal(m)
			if err != nil {
				return false, err
			}
			params = append(params, string(encodeStr))
		}
	} else {
		params = []string{}
	}

	reqWrapped := wrapperUpdateSysctParamsRequest{
		UpdateSysctParamsRequest: req,
		Params:                   params,
	}

	url := "/cloudapi/lb/updateSysctlParams"

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

	result, err := strconv.ParseBool(string(res))
	if err != nil {
		return false, err
	}

	return result, nil
}
