// 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) Go Code Generator. DO NOT EDIT.

package armsitemanager

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"
	"strings"
)

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

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

// BeginCreateOrUpdate - create or update Site at SG scope
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2025-06-01
//   - servicegroupName - The name of the service group
//   - siteName - The name of the site
//   - resource - The properties of the site
//   - options - SitesByServiceGroupClientBeginCreateOrUpdateOptions contains the optional parameters for the SitesByServiceGroupClient.BeginCreateOrUpdate
//     method.
func (client *SitesByServiceGroupClient) BeginCreateOrUpdate(ctx context.Context, servicegroupName string, siteName string, resource Site, options *SitesByServiceGroupClientBeginCreateOrUpdateOptions) (*runtime.Poller[SitesByServiceGroupClientCreateOrUpdateResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.createOrUpdate(ctx, servicegroupName, siteName, resource, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[SitesByServiceGroupClientCreateOrUpdateResponse]{
			Tracer: client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[SitesByServiceGroupClientCreateOrUpdateResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// CreateOrUpdate - create or update Site at SG scope
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2025-06-01
func (client *SitesByServiceGroupClient) createOrUpdate(ctx context.Context, servicegroupName string, siteName string, resource Site, options *SitesByServiceGroupClientBeginCreateOrUpdateOptions) (*http.Response, error) {
	var err error
	const operationName = "SitesByServiceGroupClient.BeginCreateOrUpdate"
	ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
	ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
	defer func() { endSpan(err) }()
	req, err := client.createOrUpdateCreateRequest(ctx, servicegroupName, siteName, resource, 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.StatusCreated) {
		err = runtime.NewResponseError(httpResp)
		return nil, err
	}
	return httpResp, nil
}

// createOrUpdateCreateRequest creates the CreateOrUpdate request.
func (client *SitesByServiceGroupClient) createOrUpdateCreateRequest(ctx context.Context, servicegroupName string, siteName string, resource Site, _ *SitesByServiceGroupClientBeginCreateOrUpdateOptions) (*policy.Request, error) {
	urlPath := "/providers/Microsoft.Management/serviceGroups/{servicegroupName}/providers/Microsoft.Edge/sites/{siteName}"
	if servicegroupName == "" {
		return nil, errors.New("parameter servicegroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{servicegroupName}", url.PathEscape(servicegroupName))
	if siteName == "" {
		return nil, errors.New("parameter siteName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{siteName}", url.PathEscape(siteName))
	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", "2025-06-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	req.Raw().Header["Content-Type"] = []string{"application/json"}
	if err := runtime.MarshalAsJSON(req, resource); err != nil {
		return nil, err
	}
	return req, nil
}

// Delete - delete Site at SG scope
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2025-06-01
//   - servicegroupName - The name of the service group
//   - siteName - The name of the site
//   - options - SitesByServiceGroupClientDeleteOptions contains the optional parameters for the SitesByServiceGroupClient.Delete
//     method.
func (client *SitesByServiceGroupClient) Delete(ctx context.Context, servicegroupName string, siteName string, options *SitesByServiceGroupClientDeleteOptions) (SitesByServiceGroupClientDeleteResponse, error) {
	var err error
	const operationName = "SitesByServiceGroupClient.Delete"
	ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
	ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
	defer func() { endSpan(err) }()
	req, err := client.deleteCreateRequest(ctx, servicegroupName, siteName, options)
	if err != nil {
		return SitesByServiceGroupClientDeleteResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return SitesByServiceGroupClientDeleteResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) {
		err = runtime.NewResponseError(httpResp)
		return SitesByServiceGroupClientDeleteResponse{}, err
	}
	return SitesByServiceGroupClientDeleteResponse{}, nil
}

// deleteCreateRequest creates the Delete request.
func (client *SitesByServiceGroupClient) deleteCreateRequest(ctx context.Context, servicegroupName string, siteName string, _ *SitesByServiceGroupClientDeleteOptions) (*policy.Request, error) {
	urlPath := "/providers/Microsoft.Management/serviceGroups/{servicegroupName}/providers/Microsoft.Edge/sites/{siteName}"
	if servicegroupName == "" {
		return nil, errors.New("parameter servicegroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{servicegroupName}", url.PathEscape(servicegroupName))
	if siteName == "" {
		return nil, errors.New("parameter siteName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{siteName}", url.PathEscape(siteName))
	req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2025-06-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	return req, nil
}

// Get - Get Site at SG scope
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2025-06-01
//   - servicegroupName - The name of the service group
//   - siteName - The name of the site
//   - options - SitesByServiceGroupClientGetOptions contains the optional parameters for the SitesByServiceGroupClient.Get method.
func (client *SitesByServiceGroupClient) Get(ctx context.Context, servicegroupName string, siteName string, options *SitesByServiceGroupClientGetOptions) (SitesByServiceGroupClientGetResponse, error) {
	var err error
	const operationName = "SitesByServiceGroupClient.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, servicegroupName, siteName, options)
	if err != nil {
		return SitesByServiceGroupClientGetResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return SitesByServiceGroupClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return SitesByServiceGroupClientGetResponse{}, err
	}
	resp, err := client.getHandleResponse(httpResp)
	return resp, err
}

// getCreateRequest creates the Get request.
func (client *SitesByServiceGroupClient) getCreateRequest(ctx context.Context, servicegroupName string, siteName string, _ *SitesByServiceGroupClientGetOptions) (*policy.Request, error) {
	urlPath := "/providers/Microsoft.Management/serviceGroups/{servicegroupName}/providers/Microsoft.Edge/sites/{siteName}"
	if servicegroupName == "" {
		return nil, errors.New("parameter servicegroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{servicegroupName}", url.PathEscape(servicegroupName))
	if siteName == "" {
		return nil, errors.New("parameter siteName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{siteName}", url.PathEscape(siteName))
	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", "2025-06-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

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

// NewListByServiceGroupPager - list Site at SG scope
//
// Generated from API version 2025-06-01
//   - servicegroupName - The name of the service group
//   - options - SitesByServiceGroupClientListByServiceGroupOptions contains the optional parameters for the SitesByServiceGroupClient.NewListByServiceGroupPager
//     method.
func (client *SitesByServiceGroupClient) NewListByServiceGroupPager(servicegroupName string, options *SitesByServiceGroupClientListByServiceGroupOptions) *runtime.Pager[SitesByServiceGroupClientListByServiceGroupResponse] {
	return runtime.NewPager(runtime.PagingHandler[SitesByServiceGroupClientListByServiceGroupResponse]{
		More: func(page SitesByServiceGroupClientListByServiceGroupResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *SitesByServiceGroupClientListByServiceGroupResponse) (SitesByServiceGroupClientListByServiceGroupResponse, error) {
			ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "SitesByServiceGroupClient.NewListByServiceGroupPager")
			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.listByServiceGroupCreateRequest(ctx, servicegroupName, options)
			}, nil)
			if err != nil {
				return SitesByServiceGroupClientListByServiceGroupResponse{}, err
			}
			return client.listByServiceGroupHandleResponse(resp)
		},
		Tracer: client.internal.Tracer(),
	})
}

// listByServiceGroupCreateRequest creates the ListByServiceGroup request.
func (client *SitesByServiceGroupClient) listByServiceGroupCreateRequest(ctx context.Context, servicegroupName string, _ *SitesByServiceGroupClientListByServiceGroupOptions) (*policy.Request, error) {
	urlPath := "/providers/Microsoft.Management/serviceGroups/{servicegroupName}/providers/Microsoft.Edge/sites"
	if servicegroupName == "" {
		return nil, errors.New("parameter servicegroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{servicegroupName}", url.PathEscape(servicegroupName))
	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", "2025-06-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// listByServiceGroupHandleResponse handles the ListByServiceGroup response.
func (client *SitesByServiceGroupClient) listByServiceGroupHandleResponse(resp *http.Response) (SitesByServiceGroupClientListByServiceGroupResponse, error) {
	result := SitesByServiceGroupClientListByServiceGroupResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.SiteListResult); err != nil {
		return SitesByServiceGroupClientListByServiceGroupResponse{}, err
	}
	return result, nil
}

// Update - update Site at SG scope
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2025-06-01
//   - servicegroupName - The name of the service group
//   - siteName - The name of the site
//   - properties - The properties of the site
//   - options - SitesByServiceGroupClientUpdateOptions contains the optional parameters for the SitesByServiceGroupClient.Update
//     method.
func (client *SitesByServiceGroupClient) Update(ctx context.Context, servicegroupName string, siteName string, properties SiteUpdate, options *SitesByServiceGroupClientUpdateOptions) (SitesByServiceGroupClientUpdateResponse, error) {
	var err error
	const operationName = "SitesByServiceGroupClient.Update"
	ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
	ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
	defer func() { endSpan(err) }()
	req, err := client.updateCreateRequest(ctx, servicegroupName, siteName, properties, options)
	if err != nil {
		return SitesByServiceGroupClientUpdateResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return SitesByServiceGroupClientUpdateResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return SitesByServiceGroupClientUpdateResponse{}, err
	}
	resp, err := client.updateHandleResponse(httpResp)
	return resp, err
}

// updateCreateRequest creates the Update request.
func (client *SitesByServiceGroupClient) updateCreateRequest(ctx context.Context, servicegroupName string, siteName string, properties SiteUpdate, _ *SitesByServiceGroupClientUpdateOptions) (*policy.Request, error) {
	urlPath := "/providers/Microsoft.Management/serviceGroups/{servicegroupName}/providers/Microsoft.Edge/sites/{siteName}"
	if servicegroupName == "" {
		return nil, errors.New("parameter servicegroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{servicegroupName}", url.PathEscape(servicegroupName))
	if siteName == "" {
		return nil, errors.New("parameter siteName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{siteName}", url.PathEscape(siteName))
	req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2025-06-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	req.Raw().Header["Content-Type"] = []string{"application/json"}
	if err := runtime.MarshalAsJSON(req, properties); err != nil {
		return nil, err
	}
	return req, nil
}

// updateHandleResponse handles the Update response.
func (client *SitesByServiceGroupClient) updateHandleResponse(resp *http.Response) (SitesByServiceGroupClientUpdateResponse, error) {
	result := SitesByServiceGroupClientUpdateResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.Site); err != nil {
		return SitesByServiceGroupClientUpdateResponse{}, err
	}
	return result, nil
}
