// Copyright (c) 2026 Alibaba Group and its affiliates

// 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 main

import (
	"context"
	"errors"
	"fmt"

	"github.com/dashscope/dashscope-confidential-maas/sdk"
)

var errClientPoolClosed = errors.New("client pool closed")

type pool struct {
	ch chan *sdk.Client
}

func newPool(n int, opts *sdk.Options) (*pool, error) {
	if n <= 0 {
		return nil, fmt.Errorf("workers must be positive")
	}
	p := &pool{ch: make(chan *sdk.Client, n)}
	for i := 0; i < n; i++ {
		c, err := sdk.NewClient(opts)
		if err != nil {
			return nil, fmt.Errorf("failed to create client %d: %w", i, err)
		}
		p.ch <- c
	}
	return p, nil
}

func (p *pool) acquire(ctx context.Context) (*sdk.Client, error) {
	select {
	case c, ok := <-p.ch:
		if !ok {
			return nil, errClientPoolClosed
		}
		return c, nil
	case <-ctx.Done():
		return nil, ctx.Err()
	}
}

func (p *pool) release(c *sdk.Client) {
	if c != nil {
		p.ch <- c
	}
}

func (p *pool) close() {
	close(p.ch)
	for c := range p.ch {
		c.Close()
	}
}
