// Smart URL Resolution Service für Admin-Zugriff auf Client-URLs
import debugLogger from '../utils/debugLogger';

class URLResolutionService {
  constructor() {
    // Backend-URL mit Fallback auf localhost:8000
    this.baseUrl = process.env.REACT_APP_BACKEND || 'http://localhost:8000';
    this.cache = new Map();
    this.cacheExpiry = 5 * 60 * 1000; // 5 Minuten
  }

    // Projekt-Client-Mapping vom Backend laden
  async fetchProjectClientMapping() {
    debugLogger.api('Fetching project-client mapping from backend...');
    try {
      const token = localStorage.getItem('jwt');
      if (!token) {
        debugLogger.error('Kein JWT Token verfügbar');
        throw new Error('Kein Token verfügbar');
      }

      debugLogger.api('API Request to:', `${this.baseUrl}/api/admin/project-client-mapping`);
      const response = await fetch(`${this.baseUrl}/api/admin/project-client-mapping`, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      });

      debugLogger.api('API Response Status:', response.status);
      if (!response.ok) {
        const errorText = await response.text();
        debugLogger.error('Backend Error Response:', errorText);
        throw new Error(`Backend Fehler: ${response.status} - ${errorText}`);
      }

      const data = await response.json();
      debugLogger.api('Backend Response Data:', data);
      
      if (!data.success) {
        debugLogger.error('Backend returned success=false:', data.message);
        throw new Error(data.message || 'Unbekannter Backend-Fehler');
      }

      debugLogger.success('Mapping successfully loaded:', data.mapping);
      return data.mapping || {};
    } catch (error) {
      debugLogger.error('Fehler beim Laden des Projekt-Client-Mappings:', error);
      throw error;
    }
  }

  // Gecachtes Mapping abrufen oder neu laden
  async getProjectClientMapping() {
    const cached = this.cache.get('projectClientMapping');
    if (cached && (Date.now() - cached.timestamp) < this.cacheExpiry) {
      return cached.data;
    }
    
    // Frische Daten laden und cachen
    const freshData = await this.fetchProjectClientMapping();
    this.cache.set('projectClientMapping', {
      data: freshData,
      timestamp: Date.now()
    });
    return freshData;
  }

  // Smart URL Resolution: Finde Client für ein Projekt
  async resolveClientForProject(projectName) {
    debugLogger.routing('Smart URL Resolution für Projekt:', projectName);
    
    if (!projectName) {
      debugLogger.routing('Kein Projektname angegeben');
      return null;
    }

    // Prüfe ob Admin (nur Admins dürfen URL Resolution verwenden)
    if (!this.isAdmin()) {
      debugLogger.routing('User ist kein Admin');
      return null;
    }

    try {
      debugLogger.api('Lade Projekt-Client-Mapping...');
      const mapping = await this.getProjectClientMapping();
      debugLogger.api('Erhaltenes Mapping:', mapping);
      
      const clientName = mapping[projectName] || null;
      debugLogger.success(`Projekt "${projectName}" → Client "${clientName}"`);
      
      return clientName;
    } catch (error) {
      debugLogger.error('Fehler bei URL Resolution:', error);
      return null;
    }
  }

  // Prüfe ob User Admin ist
  isAdmin() {
    const token = localStorage.getItem('jwt');
    debugLogger.auth('JWT Token check:', token ? 'Token vorhanden' : 'Kein Token');
    
    if (!token) return false;

    try {
      // JWT-Token parsen (vereinfacht)
      const payload = JSON.parse(atob(token.split('.')[1]));
      debugLogger.auth('Token Payload:', payload);
      const isAdminUser = payload.role === 'admin';
      debugLogger.auth('Is Admin:', isAdminUser);
      return isAdminUser;
    } catch (error) {
      debugLogger.error('Token parsing error:', error);
      return false;
    }
  }

  // Smart URL Resolution für Admin-Zugriff
  async resolveAdminUrl(projectName, tab = null) {
    if (!this.isAdmin()) {
      return null; // Nur für Admins
    }

    const clientName = await this.resolveClientForProject(projectName);
    if (!clientName) {
      return null; // Projekt nicht gefunden
    }

    // Konstruiere Admin-URL
    if (tab) {
      return `/${encodeURIComponent(clientName)}/${encodeURIComponent(projectName)}/${encodeURIComponent(tab)}`;
    } else {
      return `/${encodeURIComponent(clientName)}/${encodeURIComponent(projectName)}`;
    }
  }

  // Cache leeren (z.B. bei Logout)
  clearCache() {
    this.cache.clear();
  }
}

// Singleton-Instanz exportieren
const urlResolutionService = new URLResolutionService();
export default urlResolutionService;
