import AssignTagAPIService from "../../API/Tag/AssignTagAPIService.js";
import UnassignTagAPIService from "../../API/Tag/UnassignTagAPIService.js";

/**
 * FileTagManager
 *
 * Orchestrates tag assignment and management for files.
 * Handles API calls and event dispatching for tag operations on files.
 */
class FileTagManager {
  constructor(authManager, getFileManager, listFileManager) {
    this.authManager = authManager;
    this.getFileManager = getFileManager;
    this.listFileManager = listFileManager;

    // Initialize API services
    this.assignTagAPI = new AssignTagAPIService(authManager);
    this.unassignTagAPI = new UnassignTagAPIService(authManager);
  }

  /**
   * Assign tags to a file
   *
   * @param {string} fileId - UUID of the file
   * @param {Array<string>} tagIds - Array of tag UUIDs to assign
   * @returns {Promise<void>}
   */
  async assignTagsToFile(fileId, tagIds) {
    try {
      console.log("[FileTagManager] Assigning tags to file", {
        fileId,
        tagCount: tagIds.length
      });

      // Assign each tag
      for (const tagId of tagIds) {
        await this.assignTagAPI.assignTag(tagId, {
          entity_id: fileId,
          entity_type: "file"
        });
      }

      // Clear relevant caches
      this.getFileManager?.clearFileCache?.(fileId);
      this.listFileManager?.clearAllCache?.();

      // Dispatch event
      window.dispatchEvent(new CustomEvent('fileTagsAssigned', {
        detail: { fileId, tagIds }
      }));

      console.log("[FileTagManager] Tags assigned successfully");
    } catch (error) {
      console.error("[FileTagManager] Failed to assign tags:", error);
      throw error;
    }
  }

  /**
   * Unassign tags from a file
   *
   * @param {string} fileId - UUID of the file
   * @param {Array<string>} tagIds - Array of tag UUIDs to unassign
   * @returns {Promise<void>}
   */
  async unassignTagsFromFile(fileId, tagIds) {
    try {
      console.log("[FileTagManager] Unassigning tags from file", {
        fileId,
        tagCount: tagIds.length
      });

      // Unassign each tag
      for (const tagId of tagIds) {
        await this.unassignTagAPI.unassignTag(tagId, fileId, "file");
      }

      // Clear relevant caches
      this.getFileManager?.clearFileCache?.(fileId);
      this.listFileManager?.clearAllCache?.();

      // Dispatch event
      window.dispatchEvent(new CustomEvent('fileTagsUnassigned', {
        detail: { fileId, tagIds }
      }));

      console.log("[FileTagManager] Tags unassigned successfully");
    } catch (error) {
      console.error("[FileTagManager] Failed to unassign tags:", error);
      throw error;
    }
  }

  /**
   * Update file tags (replace all tags)
   *
   * @param {string} fileId - UUID of the file
   * @param {Array<string>} currentTagIds - Current tag IDs on the file
   * @param {Array<string>} newTagIds - New tag IDs to set
   * @returns {Promise<void>}
   */
  async updateFileTags(fileId, currentTagIds = [], newTagIds = []) {
    try {
      console.log("[FileTagManager] Updating file tags", {
        fileId,
        currentCount: currentTagIds.length,
        newCount: newTagIds.length
      });

      // Determine which tags to add and remove
      const tagsToAdd = newTagIds.filter(id => !currentTagIds.includes(id));
      const tagsToRemove = currentTagIds.filter(id => !newTagIds.includes(id));

      // Assign new tags
      if (tagsToAdd.length > 0) {
        await this.assignTagsToFile(fileId, tagsToAdd);
      }

      // Unassign removed tags
      if (tagsToRemove.length > 0) {
        await this.unassignTagsFromFile(fileId, tagsToRemove);
      }

      console.log("[FileTagManager] File tags updated successfully", {
        added: tagsToAdd.length,
        removed: tagsToRemove.length
      });
    } catch (error) {
      console.error("[FileTagManager] Failed to update file tags:", error);
      throw error;
    }
  }
}

export default FileTagManager;
