package discovery

import (
	"context"
	"errors"
	"fmt"
	"strings"

	"github.com/ultisuite/ulti-backend/internal/websearch"
)

var ErrWebSearchNotConfigured = errors.New("web search not configured")

func (s *Service) SearchWeb(ctx context.Context, externalUserID, query string, count int) ([]websearch.Result, error) {
	if s.websearch == nil {
		return nil, fmt.Errorf("web search unavailable")
	}
	query = strings.TrimSpace(query)
	if query == "" {
		return nil, fmt.Errorf("search query is required")
	}
	settings, err := s.loadSearchSettings(ctx, externalUserID)
	if err != nil {
		return nil, err
	}
	if !searchSettingsConfigured(settings) {
		return nil, ErrWebSearchNotConfigured
	}
	provider, err := websearch.ResolveProvider(settings)
	if err != nil {
		return nil, ErrWebSearchNotConfigured
	}
	return s.websearch.Search(ctx, provider, query, count)
}
