// Copyright 2025 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package cosmosstorageutils

import (
	"context"
	"encoding/json"
	"fmt"

	"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
	"github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos"
)

type queryResourcesIterator[InternalAPIType, CosmosAPIType any] struct {
	pager             *runtime.Pager[azcosmos.QueryItemsResponse]
	singlePage        bool
	continuationToken string
	err               error
}

// NewQueryResourcesIterator is a failable push iterator for a paged query response.
func NewQueryResourcesIterator[InternalAPIType, CosmosAPIType any](pager *runtime.Pager[azcosmos.QueryItemsResponse]) DBClientIterator[InternalAPIType] {
	return &queryResourcesIterator[InternalAPIType, CosmosAPIType]{pager: pager}
}

// NewQueryResourcesSinglePageIterator is a failable push iterator for a paged
// query response that stops at the end of the first page and includes a
// continuation token if additional items are available.
func NewQueryResourcesSinglePageIterator[InternalAPIType, CosmosAPIType any](pager *runtime.Pager[azcosmos.QueryItemsResponse]) DBClientIterator[InternalAPIType] {
	return &queryResourcesIterator[InternalAPIType, CosmosAPIType]{pager: pager, singlePage: true}
}

// Items returns a push iterator that can be used directly in for/range loops.
// If an error occurs during paging, iteration stops and the error is recorded.
func (iter *queryResourcesIterator[InternalAPIType, CosmosAPIType]) Items(ctx context.Context) DBClientIteratorItem[InternalAPIType] {
	return func(yield func(string, *InternalAPIType) bool) {
		for iter.pager.More() {
			response, err := iter.pager.NextPage(ctx)
			if err != nil {
				iter.err = err
				return
			}
			if iter.singlePage && response.ContinuationToken != nil {
				iter.continuationToken = *response.ContinuationToken
			}
			for _, itemJSON := range response.Items {
				var obj CosmosAPIType
				if err := json.Unmarshal(itemJSON, &obj); err != nil {
					iter.err = err
					return
				}
				decodedItem := &obj

				var baseDocument BaseDocument
				if err := json.Unmarshal(itemJSON, &baseDocument); err != nil {
					iter.err = err
					return
				}

				internalObj, err := CosmosToInternal[InternalAPIType, CosmosAPIType](decodedItem)
				if err != nil {
					iter.err = fmt.Errorf("failed to convert Cosmos object to internal type: %w", err)
					return
				}

				if !yield(baseDocument.ID, internalObj) {
					return
				}
			}
			if iter.singlePage {
				return
			}
		}
	}
}

// GetContinuationToken returns a continuation token that can be used to obtain
// the next page of results. This is only set when the iterator was created with
// NewQueryResourcesSinglePageIterator and additional items are available.
func (iter queryResourcesIterator[InternalAPIType, CosmosAPIType]) GetContinuationToken() string {
	return iter.continuationToken
}

// GetError returns any error that occurred during iteration. Call this after the
// for/range loop that calls Items() to check if iteration completed successfully.
func (iter queryResourcesIterator[InternalAPIType, CosmosAPIType]) GetError() error {
	return iter.err
}

type queryTypedDocumentIterator struct {
	pager             *runtime.Pager[azcosmos.QueryItemsResponse]
	singlePage        bool
	continuationToken string
	err               error
}

func NewQueryTypedDocumentIterator(pager *runtime.Pager[azcosmos.QueryItemsResponse]) DBClientIterator[TypedDocument] {
	return &queryTypedDocumentIterator{pager: pager}
}

func NewQueryTypedDocumentSinglePageIterator(pager *runtime.Pager[azcosmos.QueryItemsResponse]) DBClientIterator[TypedDocument] {
	return &queryTypedDocumentIterator{pager: pager, singlePage: true}
}

func (iter *queryTypedDocumentIterator) Items(ctx context.Context) DBClientIteratorItem[TypedDocument] {
	return func(yield func(string, *TypedDocument) bool) {
		for iter.pager.More() {
			response, err := iter.pager.NextPage(ctx)
			if err != nil {
				iter.err = err
				return
			}
			if iter.singlePage && response.ContinuationToken != nil {
				iter.continuationToken = *response.ContinuationToken
			}
			for _, itemJSON := range response.Items {
				var doc TypedDocument
				if err := json.Unmarshal(itemJSON, &doc); err != nil {
					iter.err = err
					return
				}
				if !yield(doc.ID, &doc) {
					return
				}
			}
			if iter.singlePage {
				return
			}
		}
	}
}

func (iter *queryTypedDocumentIterator) GetContinuationToken() string {
	return iter.continuationToken
}

func (iter *queryTypedDocumentIterator) GetError() error {
	return iter.err
}

// ListAll accumulates all pages from a DB GlobalLister into a slice.
// It calls listFn with a page size hint of pageSize and follows continuation tokens
// until all items have been collected.
// Any failure to list or iterate causes an early return because the caller needs the complete
// set of data to make correct decisions.
// listFn is expected to accept a opts *DBClientListResourceDocsOptions that supports
// paging via the PageSizeHint attribute.
// ListAll assists client code in breaking large list queries into multiple smaller chunks of pageSize or smaller. This
// helps reduce the load on the database at the cost of more round trips.
// pageSize determines the maximum number of items to be retrieved at once. A negative value will set a dynamic
// page size controlled by Cosmos.
func ListAll[InternalAPIType any](
	ctx context.Context,
	pageSize int32,
	listFn func(ctx context.Context, opts *DBClientListResourceDocsOptions) (DBClientIterator[InternalAPIType], error),
) ([]*InternalAPIType, error) {
	opts := &DBClientListResourceDocsOptions{
		PageSizeHint: &pageSize,
	}
	all := make([]*InternalAPIType, 0)
	for {
		iterator, err := listFn(ctx, opts)
		if err != nil {
			return nil, fmt.Errorf("failed to list: %w", err)
		}
		for _, item := range iterator.Items(ctx) {
			all = append(all, item)
		}
		if err := iterator.GetError(); err != nil {
			return nil, fmt.Errorf("failed iterating: %w", err)
		}
		token := iterator.GetContinuationToken()
		if token == "" {
			break
		}
		opts.ContinuationToken = &token
	}
	return all, nil
}
