/**
 * ListCollectionsByTagAPIService
 *
 * Service for fetching collections filtered by tags.
 * Calls the backend API: GET /api/v1/tags/collections?tags=uuid1,uuid2
 */
class ListCollectionsByTagAPIService {
  constructor(authManager) {
    this.authManager = authManager;
    this._apiClient = null;
  }

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

  /**
   * Get collections that have ALL specified tags (AND logic)
   *
   * @param {Array<string>} tagIds - Array of tag UUIDs
   * @param {Object} options - Query options
   * @param {number} options.limit - Number of results to return (default: 50, max: 100)
   * @param {string} options.cursor - Pagination cursor
   * @returns {Promise<Object>} - Response with collections array, cursor, has_more, tag_count
   */
  async getCollectionsByTags(tagIds, options = {}) {
    try {
      if (!tagIds || tagIds.length === 0) {
        console.warn("[ListCollectionsByTagAPIService] No tag IDs provided");
        return { collections: [], cursor: "", has_more: false, tag_count: 0 };
      }

      console.log("[ListCollectionsByTagAPIService] Fetching collections by tags", {
        tagIds,
        options
      });

      const apiClient = await this.getApiClient();

      // Build query string
      const params = new URLSearchParams();
      params.append('tags', tagIds.join(','));
      if (options.limit) params.append('limit', options.limit);
      if (options.cursor) params.append('cursor', options.cursor);

      const response = await apiClient.getMapleFile(
        `/tags/collections?${params.toString()}`
      );

      console.log("[ListCollectionsByTagAPIService] Collections fetched successfully", {
        count: response.collections?.length || 0,
        has_more: response.has_more
      });

      return response;
    } catch (error) {
      console.error("[ListCollectionsByTagAPIService] Failed to fetch collections:", error);
      throw error;
    }
  }
}

export default ListCollectionsByTagAPIService;
