//go:build go1.18
// +build go1.18

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

package armsupport

import (
	"context"
	"errors"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
	"net/http"
	"net/url"
	"strconv"
	"strings"
)

// CommunicationsNoSubscriptionClient contains the methods for the CommunicationsNoSubscription group.
// Don't use this type directly, use NewCommunicationsNoSubscriptionClient() instead.
type CommunicationsNoSubscriptionClient struct {
	internal *arm.Client
}

// NewCommunicationsNoSubscriptionClient creates a new instance of CommunicationsNoSubscriptionClient with the specified values.
//   - credential - used to authorize requests. Usually a credential from azidentity.
//   - options - pass nil to accept the default values.
func NewCommunicationsNoSubscriptionClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*CommunicationsNoSubscriptionClient, error) {
	cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
	if err != nil {
		return nil, err
	}
	client := &CommunicationsNoSubscriptionClient{
		internal: cl,
	}
	return client, nil
}

// CheckNameAvailability - Check the availability of a resource name. This API should be used to check the uniqueness of the
// name for adding a new communication to the support ticket.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2024-04-01
//   - supportTicketName - Support ticket name.
//   - checkNameAvailabilityInput - Input to check.
//   - options - CommunicationsNoSubscriptionClientCheckNameAvailabilityOptions contains the optional parameters for the CommunicationsNoSubscriptionClient.CheckNameAvailability
//     method.
func (client *CommunicationsNoSubscriptionClient) CheckNameAvailability(ctx context.Context, supportTicketName string, checkNameAvailabilityInput CheckNameAvailabilityInput, options *CommunicationsNoSubscriptionClientCheckNameAvailabilityOptions) (CommunicationsNoSubscriptionClientCheckNameAvailabilityResponse, error) {
	var err error
	const operationName = "CommunicationsNoSubscriptionClient.CheckNameAvailability"
	ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
	ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
	defer func() { endSpan(err) }()
	req, err := client.checkNameAvailabilityCreateRequest(ctx, supportTicketName, checkNameAvailabilityInput, options)
	if err != nil {
		return CommunicationsNoSubscriptionClientCheckNameAvailabilityResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return CommunicationsNoSubscriptionClientCheckNameAvailabilityResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return CommunicationsNoSubscriptionClientCheckNameAvailabilityResponse{}, err
	}
	resp, err := client.checkNameAvailabilityHandleResponse(httpResp)
	return resp, err
}

// checkNameAvailabilityCreateRequest creates the CheckNameAvailability request.
func (client *CommunicationsNoSubscriptionClient) checkNameAvailabilityCreateRequest(ctx context.Context, supportTicketName string, checkNameAvailabilityInput CheckNameAvailabilityInput, options *CommunicationsNoSubscriptionClientCheckNameAvailabilityOptions) (*policy.Request, error) {
	urlPath := "/providers/Microsoft.Support/supportTickets/{supportTicketName}/checkNameAvailability"
	if supportTicketName == "" {
		return nil, errors.New("parameter supportTicketName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{supportTicketName}", url.PathEscape(supportTicketName))
	req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2024-04-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	if err := runtime.MarshalAsJSON(req, checkNameAvailabilityInput); err != nil {
		return nil, err
	}
	return req, nil
}

// checkNameAvailabilityHandleResponse handles the CheckNameAvailability response.
func (client *CommunicationsNoSubscriptionClient) checkNameAvailabilityHandleResponse(resp *http.Response) (CommunicationsNoSubscriptionClientCheckNameAvailabilityResponse, error) {
	result := CommunicationsNoSubscriptionClientCheckNameAvailabilityResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.CheckNameAvailabilityOutput); err != nil {
		return CommunicationsNoSubscriptionClientCheckNameAvailabilityResponse{}, err
	}
	return result, nil
}

// BeginCreate - Adds a new customer communication to an Azure support ticket.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2024-04-01
//   - supportTicketName - Support ticket name.
//   - communicationName - Communication name.
//   - createCommunicationParameters - Communication object.
//   - options - CommunicationsNoSubscriptionClientBeginCreateOptions contains the optional parameters for the CommunicationsNoSubscriptionClient.BeginCreate
//     method.
func (client *CommunicationsNoSubscriptionClient) BeginCreate(ctx context.Context, supportTicketName string, communicationName string, createCommunicationParameters CommunicationDetails, options *CommunicationsNoSubscriptionClientBeginCreateOptions) (*runtime.Poller[CommunicationsNoSubscriptionClientCreateResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.create(ctx, supportTicketName, communicationName, createCommunicationParameters, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CommunicationsNoSubscriptionClientCreateResponse]{
			FinalStateVia: runtime.FinalStateViaAzureAsyncOp,
			Tracer:        client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CommunicationsNoSubscriptionClientCreateResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// Create - Adds a new customer communication to an Azure support ticket.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2024-04-01
func (client *CommunicationsNoSubscriptionClient) create(ctx context.Context, supportTicketName string, communicationName string, createCommunicationParameters CommunicationDetails, options *CommunicationsNoSubscriptionClientBeginCreateOptions) (*http.Response, error) {
	var err error
	const operationName = "CommunicationsNoSubscriptionClient.BeginCreate"
	ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
	ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
	defer func() { endSpan(err) }()
	req, err := client.createCreateRequest(ctx, supportTicketName, communicationName, createCommunicationParameters, options)
	if err != nil {
		return nil, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return nil, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) {
		err = runtime.NewResponseError(httpResp)
		return nil, err
	}
	return httpResp, nil
}

// createCreateRequest creates the Create request.
func (client *CommunicationsNoSubscriptionClient) createCreateRequest(ctx context.Context, supportTicketName string, communicationName string, createCommunicationParameters CommunicationDetails, options *CommunicationsNoSubscriptionClientBeginCreateOptions) (*policy.Request, error) {
	urlPath := "/providers/Microsoft.Support/supportTickets/{supportTicketName}/communications/{communicationName}"
	if supportTicketName == "" {
		return nil, errors.New("parameter supportTicketName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{supportTicketName}", url.PathEscape(supportTicketName))
	if communicationName == "" {
		return nil, errors.New("parameter communicationName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{communicationName}", url.PathEscape(communicationName))
	req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2024-04-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	if err := runtime.MarshalAsJSON(req, createCommunicationParameters); err != nil {
		return nil, err
	}
	return req, nil
}

// Get - Returns communication details for a support ticket.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2024-04-01
//   - supportTicketName - Support ticket name.
//   - communicationName - Communication name.
//   - options - CommunicationsNoSubscriptionClientGetOptions contains the optional parameters for the CommunicationsNoSubscriptionClient.Get
//     method.
func (client *CommunicationsNoSubscriptionClient) Get(ctx context.Context, supportTicketName string, communicationName string, options *CommunicationsNoSubscriptionClientGetOptions) (CommunicationsNoSubscriptionClientGetResponse, error) {
	var err error
	const operationName = "CommunicationsNoSubscriptionClient.Get"
	ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
	ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
	defer func() { endSpan(err) }()
	req, err := client.getCreateRequest(ctx, supportTicketName, communicationName, options)
	if err != nil {
		return CommunicationsNoSubscriptionClientGetResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return CommunicationsNoSubscriptionClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return CommunicationsNoSubscriptionClientGetResponse{}, err
	}
	resp, err := client.getHandleResponse(httpResp)
	return resp, err
}

// getCreateRequest creates the Get request.
func (client *CommunicationsNoSubscriptionClient) getCreateRequest(ctx context.Context, supportTicketName string, communicationName string, options *CommunicationsNoSubscriptionClientGetOptions) (*policy.Request, error) {
	urlPath := "/providers/Microsoft.Support/supportTickets/{supportTicketName}/communications/{communicationName}"
	if supportTicketName == "" {
		return nil, errors.New("parameter supportTicketName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{supportTicketName}", url.PathEscape(supportTicketName))
	if communicationName == "" {
		return nil, errors.New("parameter communicationName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{communicationName}", url.PathEscape(communicationName))
	req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2024-04-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// getHandleResponse handles the Get response.
func (client *CommunicationsNoSubscriptionClient) getHandleResponse(resp *http.Response) (CommunicationsNoSubscriptionClientGetResponse, error) {
	result := CommunicationsNoSubscriptionClientGetResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.CommunicationDetails); err != nil {
		return CommunicationsNoSubscriptionClientGetResponse{}, err
	}
	return result, nil
}

// NewListPager - Lists all communications (attachments not included) for a support ticket.
// You can also filter support ticket communications by CreatedDate or CommunicationType using the $filter parameter. The
// only type of communication supported today is Web. Output will be a paged result
// with nextLink, using which you can retrieve the next set of Communication results.
// Support ticket data is available for 18 months after ticket creation. If a ticket was created more than 18 months ago,
// a request for data might cause an error.
//
// Generated from API version 2024-04-01
//   - supportTicketName - Support ticket name
//   - options - CommunicationsNoSubscriptionClientListOptions contains the optional parameters for the CommunicationsNoSubscriptionClient.NewListPager
//     method.
func (client *CommunicationsNoSubscriptionClient) NewListPager(supportTicketName string, options *CommunicationsNoSubscriptionClientListOptions) *runtime.Pager[CommunicationsNoSubscriptionClientListResponse] {
	return runtime.NewPager(runtime.PagingHandler[CommunicationsNoSubscriptionClientListResponse]{
		More: func(page CommunicationsNoSubscriptionClientListResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *CommunicationsNoSubscriptionClientListResponse) (CommunicationsNoSubscriptionClientListResponse, error) {
			ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CommunicationsNoSubscriptionClient.NewListPager")
			nextLink := ""
			if page != nil {
				nextLink = *page.NextLink
			}
			resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
				return client.listCreateRequest(ctx, supportTicketName, options)
			}, nil)
			if err != nil {
				return CommunicationsNoSubscriptionClientListResponse{}, err
			}
			return client.listHandleResponse(resp)
		},
		Tracer: client.internal.Tracer(),
	})
}

// listCreateRequest creates the List request.
func (client *CommunicationsNoSubscriptionClient) listCreateRequest(ctx context.Context, supportTicketName string, options *CommunicationsNoSubscriptionClientListOptions) (*policy.Request, error) {
	urlPath := "/providers/Microsoft.Support/supportTickets/{supportTicketName}/communications"
	if supportTicketName == "" {
		return nil, errors.New("parameter supportTicketName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{supportTicketName}", url.PathEscape(supportTicketName))
	req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	if options != nil && options.Filter != nil {
		reqQP.Set("$filter", *options.Filter)
	}
	if options != nil && options.Top != nil {
		reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10))
	}
	reqQP.Set("api-version", "2024-04-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// listHandleResponse handles the List response.
func (client *CommunicationsNoSubscriptionClient) listHandleResponse(resp *http.Response) (CommunicationsNoSubscriptionClientListResponse, error) {
	result := CommunicationsNoSubscriptionClientListResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.CommunicationsListResult); err != nil {
		return CommunicationsNoSubscriptionClientListResponse{}, err
	}
	return result, nil
}
