// File: monorepo/web/maplefile-frontend/src/services/API/Tag/UpdateTagAPIService.js
// Update Tag API Service - Handles tag updates

class UpdateTagAPIService {
  constructor(authManager) {
    this.authManager = authManager;
    this._apiClient = null;
    console.log(
      "[UpdateTagAPIService] 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;
  }

  // Update tag via API
  async updateTag(tagId, tagData) {
    try {
      console.log("[UpdateTagAPIService] Updating tag via API:", tagId);
      console.log("[UpdateTagAPIService] Tag data:", {
        hasEncryptedName: !!tagData.encrypted_name,
        hasEncryptedColor: !!tagData.encrypted_color,
        hasEncryptedKey: !!tagData.encrypted_tag_key,
      });

      // Validate tag data before sending to API
      this.validateTagData(tagData);

      const apiClient = await this.getApiClient();
      const response = await apiClient.putMapleFile(`/tags/${tagId}`, tagData);

      console.log("[UpdateTagAPIService] Tag updated successfully");
      return response;
    } catch (error) {
      console.error("[UpdateTagAPIService] Tag update failed:", error);
      throw error;
    }
  }

  // Validate tag data before API call
  validateTagData(tagData) {
    const requiredFields = [
      "id",
      "encrypted_name",
      "encrypted_color",
      "encrypted_tag_key",
    ];
    const errors = [];

    requiredFields.forEach((field) => {
      if (!tagData[field]) {
        errors.push(`Missing required field: ${field}`);
      }
    });

    // Validate encrypted_tag_key structure
    if (tagData.encrypted_tag_key) {
      const keyData = tagData.encrypted_tag_key;
      if (!keyData.ciphertext || !keyData.nonce) {
        errors.push("encrypted_tag_key must have ciphertext and nonce");
      }
    }

    if (errors.length > 0) {
      throw new Error(`Validation failed: ${errors.join(", ")}`);
    }

    return true;
  }

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

export default UpdateTagAPIService;
