// File: monorepo/web/maplefile-frontend/src/services/API/Tag/SearchByTagsAPIService.js
// Search By Tags API Service - Handles multi-tag searching for collections and files

class SearchByTagsAPIService {
  constructor(authManager) {
    this.authManager = authManager;
    this._apiClient = null;
    console.log(
      "[SearchByTagsAPIService] API service initialized with AuthManager dependency",
    );
  }

  // Import ApiClient for authenticated requests
  async getApiClient() {
    if (!this._apiClient) {
      const { default: ApiClient } = await import("../ApiClient.js");
      this._apiClient = ApiClient;
    }
    return this._apiClient;
  }

  /**
   * Search for collections and files by tags (AND logic - items must have ALL selected tags)
   * @param {Array<string>} tagIds - Array of tag UUIDs to search for
   * @param {number} limit - Maximum number of results (default 50, max 100 on backend)
   * @returns {Promise<Object>} - Object with collections, files, and counts
   */
  async searchByTags(tagIds, limit = 50) {
    try {
      console.log("[SearchByTagsAPIService] Searching by tags:", tagIds);

      if (!tagIds || tagIds.length === 0) {
        throw new Error("At least one tag ID is required");
      }

      // Build query string with comma-separated tag IDs
      const tagsParam = tagIds.join(",");
      const queryParams = new URLSearchParams({
        tags: tagsParam,
        limit: limit.toString(),
      });

      const apiClient = await this.getApiClient();
      const response = await apiClient.getMapleFile(`/tags/search?${queryParams}`);

      console.log(
        "[SearchByTagsAPIService] Search results:",
        response.collection_count,
        "collections,",
        response.file_count,
        "files",
      );

      return {
        collections: response?.collections || [],
        files: response?.files || [],
        tagCount: response?.tag_count || 0,
        collectionCount: response?.collection_count || 0,
        fileCount: response?.file_count || 0,
      };
    } catch (error) {
      console.error("[SearchByTagsAPIService] Failed to search by tags:", error);
      throw error;
    }
  }

  // Get debug information
  getDebugInfo() {
    return {
      serviceName: "SearchByTagsAPIService",
      managedBy: "AuthManager",
      isAuthenticated: this.authManager.isAuthenticated(),
      canMakeRequests: this.authManager.canMakeAuthenticatedRequests(),
    };
  }
}

export default SearchByTagsAPIService;
