package secgroup

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

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

type UpdateRequest struct {
	// Security group ID
	// Required: true
	SecurityGroupID uint64 `url:"security_group_id" json:"security_group_id" validate:"required"`

	// New security group name
	// Required: false
	Name string `url:"name,omitempty" json:"name,omitempty"`

	// New security group description
	// Required: false
	Description string `url:"description,omitempty" json:"description,omitempty"`
}

func (sg SecurityGroup) Update(ctx context.Context, req UpdateRequest) (*RecordSecurityGroup, error) {
	res, err := sg.UpdateRaw(ctx, req)
	if err != nil {
		return nil, err
	}

	info := RecordSecurityGroup{}

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

	return &info, nil
}

func (sg SecurityGroup) UpdateRaw(ctx context.Context, req UpdateRequest) ([]byte, error) {
	err := validators.ValidateRequest(req)
	if err != nil {
		return nil, validators.ValidationErrors(validators.GetErrors(err))
	}

	url := "/cloudapi/security_group/update"

	res, err := sg.client.DecortApiCall(ctx, http.MethodPost, url, req)
	return res, err
}
