// File: monorepo/web/maplefile-frontend/src/services/Manager/BlockedEmailManager.js
// Blocked Email Manager - Orchestrates API service for blocked email management

import BlockedEmailAPIService from "../API/BlockedEmailAPIService.js";

class BlockedEmailManager {
  constructor(authManager) {
    // BlockedEmailManager depends on AuthManager for authentication
    this.authManager = authManager;
    this.isLoading = false;
    this.isInitialized = false;

    // Cache for blocked emails list
    this._cachedBlockedEmails = null;
    this._cacheTimestamp = null;
    this._cacheTimeout = 5 * 60 * 1000; // 5 minutes

    // Initialize API service
    this.apiService = new BlockedEmailAPIService(authManager);

    console.log(
      "[BlockedEmailManager] Blocked email manager initialized with AuthManager dependency",
    );
  }

  // Initialize the manager
  async initialize() {
    try {
      console.log("[BlockedEmailManager] Initializing blocked email manager...");
      this.isInitialized = true;
      console.log(
        "[BlockedEmailManager] Blocked email manager initialized successfully",
      );
    } catch (error) {
      console.error(
        "[BlockedEmailManager] Failed to initialize blocked email manager:",
        error,
      );
    }
  }

  // === Blocked Email Management ===

  // Get list of blocked emails
  async getBlockedEmails(forceRefresh = false) {
    if (!this.authManager.isAuthenticated()) {
      throw new Error("User not authenticated via AuthManager");
    }

    try {
      this.isLoading = true;
      console.log("[BlockedEmailManager] Getting blocked emails list");

      // Check cache first if not forcing refresh
      if (!forceRefresh && this._isCacheFresh()) {
        console.log("[BlockedEmailManager] Returning cached blocked emails");
        return this._cachedBlockedEmails;
      }

      // Fetch from API
      console.log("[BlockedEmailManager] Fetching blocked emails from API");
      const response = await this.apiService.listBlockedEmails();

      // Update cache
      this._cachedBlockedEmails = response.blocked_emails || [];
      this._cacheTimestamp = Date.now();

      console.log(
        "[BlockedEmailManager] Blocked emails retrieved:",
        this._cachedBlockedEmails.length,
        "entries",
      );

      return this._cachedBlockedEmails;
    } catch (error) {
      console.error("[BlockedEmailManager] Failed to get blocked emails:", error);
      throw error;
    } finally {
      this.isLoading = false;
    }
  }

  // Add an email to the blocked list
  async addBlockedEmail(email) {
    if (!this.authManager.isAuthenticated()) {
      throw new Error("User not authenticated via AuthManager");
    }

    if (!email) {
      throw new Error("Email address is required");
    }

    try {
      this.isLoading = true;
      console.log("[BlockedEmailManager] Adding email to blocked list:", email);

      // Create via API
      const response = await this.apiService.createBlockedEmail(email);

      // Invalidate cache
      this._invalidateCache();

      console.log("[BlockedEmailManager] Email added to blocked list successfully");
      return response;
    } catch (error) {
      console.error("[BlockedEmailManager] Failed to add blocked email:", error);
      throw error;
    } finally {
      this.isLoading = false;
    }
  }

  // Remove an email from the blocked list
  async removeBlockedEmail(email) {
    if (!this.authManager.isAuthenticated()) {
      throw new Error("User not authenticated via AuthManager");
    }

    if (!email) {
      throw new Error("Email address is required");
    }

    try {
      this.isLoading = true;
      console.log("[BlockedEmailManager] Removing email from blocked list:", email);

      // Delete via API
      const response = await this.apiService.deleteBlockedEmail(email);

      // Invalidate cache
      this._invalidateCache();

      console.log(
        "[BlockedEmailManager] Email removed from blocked list successfully",
      );
      return response;
    } catch (error) {
      console.error("[BlockedEmailManager] Failed to remove blocked email:", error);
      throw error;
    } finally {
      this.isLoading = false;
    }
  }

  // Check if an email is blocked (checks cache)
  async isEmailBlocked(email) {
    try {
      const blockedEmails = await this.getBlockedEmails();
      const normalizedEmail = email.toLowerCase().trim();
      return blockedEmails.some(
        (blocked) => blocked.blocked_email.toLowerCase() === normalizedEmail,
      );
    } catch (error) {
      console.error("[BlockedEmailManager] Failed to check if email is blocked:", error);
      return false; // Default to not blocked on error
    }
  }

  // === Cache Management ===

  _isCacheFresh() {
    if (!this._cachedBlockedEmails || !this._cacheTimestamp) {
      return false;
    }
    return Date.now() - this._cacheTimestamp < this._cacheTimeout;
  }

  _invalidateCache() {
    this._cachedBlockedEmails = null;
    this._cacheTimestamp = null;
    console.log("[BlockedEmailManager] Cache invalidated");
  }

  // Clear all cached data
  clearCache() {
    this._invalidateCache();
  }

  // Set cache timeout
  setCacheTimeout(timeoutMs) {
    this._cacheTimeout = timeoutMs;
    console.log("[BlockedEmailManager] Cache timeout set to:", timeoutMs, "ms");
  }

  // === State Management ===

  // Get loading state
  isLoadingData() {
    return this.isLoading;
  }

  // Get cached data without making API call
  getCachedBlockedEmails() {
    return this._cachedBlockedEmails || [];
  }

  // Get the count of blocked emails
  getBlockedEmailCount() {
    return this._cachedBlockedEmails ? this._cachedBlockedEmails.length : 0;
  }

  // === Manager Status ===

  getManagerStatus() {
    return {
      isLoading: this.isLoading,
      isInitialized: this.isInitialized,
      isAuthenticated: this.authManager.isAuthenticated(),
      cacheStatus: {
        isFresh: this._isCacheFresh(),
        count: this.getBlockedEmailCount(),
        lastUpdated: this._cacheTimestamp
          ? new Date(this._cacheTimestamp).toISOString()
          : null,
      },
    };
  }

  // === Debug Information ===

  getDebugInfo() {
    return {
      serviceName: "BlockedEmailManager",
      role: "orchestrator",
      type: "authenticated_service",
      apiService: this.apiService.getDebugInfo(),
      managerStatus: this.getManagerStatus(),
    };
  }
}

export default BlockedEmailManager;
