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

// SitesBySubscriptionClient contains the methods for the SitesBySubscription group.
// Don't use this type directly, use NewSitesBySubscriptionClient() instead.
type SitesBySubscriptionClient struct {
	internal       *arm.Client
	subscriptionID string
}

// NewSitesBySubscriptionClient creates a new instance of SitesBySubscriptionClient with the specified values.
//   - subscriptionID - The ID of the target subscription. The value must be an UUID.
//   - credential - used to authorize requests. Usually a credential from azidentity.
//   - options - pass nil to accept the default values.
func NewSitesBySubscriptionClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*SitesBySubscriptionClient, error) {
	cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
	if err != nil {
		return nil, err
	}
	client := &SitesBySubscriptionClient{
		subscriptionID: subscriptionID,
		internal:       cl,
	}
	return client, nil
}

// BeginCreateOrUpdate - Create a Site
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2025-06-01
//   - siteName - Name of Site resource
//   - resource - Resource create parameters.
//   - options - SitesBySubscriptionClientBeginCreateOrUpdateOptions contains the optional parameters for the SitesBySubscriptionClient.BeginCreateOrUpdate
//     method.
func (client *SitesBySubscriptionClient) BeginCreateOrUpdate(ctx context.Context, siteName string, resource Site, options *SitesBySubscriptionClientBeginCreateOrUpdateOptions) (*runtime.Poller[SitesBySubscriptionClientCreateOrUpdateResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.createOrUpdate(ctx, siteName, resource, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[SitesBySubscriptionClientCreateOrUpdateResponse]{
			Tracer: client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[SitesBySubscriptionClientCreateOrUpdateResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// CreateOrUpdate - Create a Site
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2025-06-01
func (client *SitesBySubscriptionClient) createOrUpdate(ctx context.Context, siteName string, resource Site, options *SitesBySubscriptionClientBeginCreateOrUpdateOptions) (*http.Response, error) {
	var err error
	const operationName = "SitesBySubscriptionClient.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, 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 *SitesBySubscriptionClient) createOrUpdateCreateRequest(ctx context.Context, siteName string, resource Site, _ *SitesBySubscriptionClientBeginCreateOrUpdateOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Edge/sites/{siteName}"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	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 a Site
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2025-06-01
//   - siteName - Name of Site resource
//   - options - SitesBySubscriptionClientDeleteOptions contains the optional parameters for the SitesBySubscriptionClient.Delete
//     method.
func (client *SitesBySubscriptionClient) Delete(ctx context.Context, siteName string, options *SitesBySubscriptionClientDeleteOptions) (SitesBySubscriptionClientDeleteResponse, error) {
	var err error
	const operationName = "SitesBySubscriptionClient.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, siteName, options)
	if err != nil {
		return SitesBySubscriptionClientDeleteResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return SitesBySubscriptionClientDeleteResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) {
		err = runtime.NewResponseError(httpResp)
		return SitesBySubscriptionClientDeleteResponse{}, err
	}
	return SitesBySubscriptionClientDeleteResponse{}, nil
}

// deleteCreateRequest creates the Delete request.
func (client *SitesBySubscriptionClient) deleteCreateRequest(ctx context.Context, siteName string, _ *SitesBySubscriptionClientDeleteOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Edge/sites/{siteName}"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	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 a Site
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2025-06-01
//   - siteName - Name of Site resource
//   - options - SitesBySubscriptionClientGetOptions contains the optional parameters for the SitesBySubscriptionClient.Get method.
func (client *SitesBySubscriptionClient) Get(ctx context.Context, siteName string, options *SitesBySubscriptionClientGetOptions) (SitesBySubscriptionClientGetResponse, error) {
	var err error
	const operationName = "SitesBySubscriptionClient.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, siteName, options)
	if err != nil {
		return SitesBySubscriptionClientGetResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return SitesBySubscriptionClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return SitesBySubscriptionClientGetResponse{}, err
	}
	resp, err := client.getHandleResponse(httpResp)
	return resp, err
}

// getCreateRequest creates the Get request.
func (client *SitesBySubscriptionClient) getCreateRequest(ctx context.Context, siteName string, _ *SitesBySubscriptionClientGetOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Edge/sites/{siteName}"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	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 *SitesBySubscriptionClient) getHandleResponse(resp *http.Response) (SitesBySubscriptionClientGetResponse, error) {
	result := SitesBySubscriptionClientGetResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.Site); err != nil {
		return SitesBySubscriptionClientGetResponse{}, err
	}
	return result, nil
}

// NewListPager - List Site resources by subscription ID
//
// Generated from API version 2025-06-01
//   - options - SitesBySubscriptionClientListOptions contains the optional parameters for the SitesBySubscriptionClient.NewListPager
//     method.
func (client *SitesBySubscriptionClient) NewListPager(options *SitesBySubscriptionClientListOptions) *runtime.Pager[SitesBySubscriptionClientListResponse] {
	return runtime.NewPager(runtime.PagingHandler[SitesBySubscriptionClientListResponse]{
		More: func(page SitesBySubscriptionClientListResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *SitesBySubscriptionClientListResponse) (SitesBySubscriptionClientListResponse, error) {
			ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "SitesBySubscriptionClient.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, options)
			}, nil)
			if err != nil {
				return SitesBySubscriptionClientListResponse{}, err
			}
			return client.listHandleResponse(resp)
		},
		Tracer: client.internal.Tracer(),
	})
}

// listCreateRequest creates the List request.
func (client *SitesBySubscriptionClient) listCreateRequest(ctx context.Context, _ *SitesBySubscriptionClientListOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Edge/sites"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	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
}

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

// Update - Update a Site
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2025-06-01
//   - siteName - Name of Site resource
//   - properties - The resource properties to be updated.
//   - options - SitesBySubscriptionClientUpdateOptions contains the optional parameters for the SitesBySubscriptionClient.Update
//     method.
func (client *SitesBySubscriptionClient) Update(ctx context.Context, siteName string, properties SiteUpdate, options *SitesBySubscriptionClientUpdateOptions) (SitesBySubscriptionClientUpdateResponse, error) {
	var err error
	const operationName = "SitesBySubscriptionClient.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, siteName, properties, options)
	if err != nil {
		return SitesBySubscriptionClientUpdateResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return SitesBySubscriptionClientUpdateResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return SitesBySubscriptionClientUpdateResponse{}, err
	}
	resp, err := client.updateHandleResponse(httpResp)
	return resp, err
}

// updateCreateRequest creates the Update request.
func (client *SitesBySubscriptionClient) updateCreateRequest(ctx context.Context, siteName string, properties SiteUpdate, _ *SitesBySubscriptionClientUpdateOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Edge/sites/{siteName}"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	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 *SitesBySubscriptionClient) updateHandleResponse(resp *http.Response) (SitesBySubscriptionClientUpdateResponse, error) {
	result := SitesBySubscriptionClientUpdateResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.Site); err != nil {
		return SitesBySubscriptionClientUpdateResponse{}, err
	}
	return result, nil
}
