package secgroup

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

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

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

	// Traffic direction (inbound/outbound)
	// Required: true
	Direction string `url:"direction" json:"direction" validate:"required,securityGroupDirection"`

	// IP protocol version
	// Default: IPv4
	// Required: false
	Ethertype string `url:"ethertype,omitempty" json:"ethertype,omitempty" validate:"omitempty,securityGroupEthertype"`

	// Network protocol, available values : icmp, tcp, udp
	// Required: false
	Protocol string `url:"protocol,omitempty" json:"protocol,omitempty" validate:"omitempty,securityGroupProtocol"`

	// Start port number (for TCP/UDP)
	// Required: false
	PortRangeMin uint64 `url:"port_range_min,omitempty" json:"port_range_min,omitempty"`

	// End port number (for TCP/UDP)
	// Required: false
	PortRangeMax uint64 `url:"port_range_max,omitempty" json:"port_range_max,omitempty"`

	// Remote IP prefix in CIDR notation
	// Required: false
	RemoteIPPrefix string `url:"remote_ip_prefix,omitempty" json:"remote_ip_prefix,omitempty"`
}

func (sg SecurityGroup) CreateRule(ctx context.Context, req CreateRuleRequest) (uint64, error) {
	err := validators.ValidateRequest(req)
	if err != nil {
		return 0, validators.ValidationErrors(validators.GetErrors(err))
	}

	url := "/cloudapi/security_group/create_rule"

	res, err := sg.client.DecortApiCallCtype(ctx, http.MethodPost, url, constants.MIMEJSON, req)
	if err != nil {
		return 0, err
	}

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

	return result, nil

}
