const fs = require('fs');
const path = require('path');

// Load API mapping configuration
function loadApiMapping() {
  try {
    const mappingPath = path.join(__dirname, '../config/api-mapping.json');
    const mappingData = fs.readFileSync(mappingPath, 'utf8');
    return JSON.parse(mappingData);
  } catch (error) {
    console.error('❌ Lỗi khi load API mapping:', error);
    return null;
  }
}

// Get API server URL based on domain
function getApiServerByDomain(domain) {
  try {
    const mapping = loadApiMapping();
    if (!mapping) {
      throw new Error('Không thể load API mapping configuration');
    }

    // Normalize domain (remove protocol, port, path)
    const normalizedDomain = normalizeDomain(domain);
    console.log('🔍 Tìm API server cho domain:', normalizedDomain);

    // Check if domain exists in mapping
    if (mapping.api_mapping[normalizedDomain]) {
      const apiConfig = mapping.api_mapping[normalizedDomain];
      console.log('✅ Tìm thấy API mapping:', {
        domain: normalizedDomain,
        api_server: apiConfig.api_server,
        environment: apiConfig.environment,
        description: apiConfig.description
      });
      return apiConfig.api_server;
    }

    // Check for subdomain matching
    const subdomainMatch = findSubdomainMatch(normalizedDomain, mapping.api_mapping);
    if (subdomainMatch) {
      const apiConfig = mapping.api_mapping[subdomainMatch];
      console.log('✅ Tìm thấy subdomain match:', {
        original_domain: normalizedDomain,
        matched_domain: subdomainMatch,
        api_server: apiConfig.api_server,
        environment: apiConfig.environment
      });
      return apiConfig.api_server;
    }

    // Không tìm thấy mapping - trả về lỗi
    const errorMsg = `Không tìm thấy API mapping cho domain: ${normalizedDomain}`;
    console.error('❌', errorMsg);
    throw new Error(errorMsg);

  } catch (error) {
    console.error('❌ Lỗi khi get API server:', error);
    throw error; // Re-throw error thay vì fallback
  }
}

// Normalize domain (remove protocol, port, path)
function normalizeDomain(domain) {
  if (!domain || domain.trim() === '') {
    throw new Error('Domain không được để trống');
  }
  
  // Remove protocol
  let normalized = domain.replace(/^https?:\/\//, '');
  
  // Remove path
  normalized = normalized.split('/')[0];
  
  // Remove www prefix
  normalized = normalized.replace(/^www\./, '');
  
  // Check if domain is valid
  if (!normalized || normalized.trim() === '') {
    throw new Error('Domain không hợp lệ sau khi normalize');
  }
  
  return normalized.toLowerCase();
}

// Find subdomain match
function findSubdomainMatch(domain, apiMapping) {
  const domainParts = domain.split('.');
  
  // Try different subdomain combinations
  for (let i = 0; i < domainParts.length - 1; i++) {
    const subdomain = domainParts.slice(i).join('.');
    if (apiMapping[subdomain]) {
      return subdomain;
    }
  }
  
  return null;
}

// Get environment info by domain
function getEnvironmentInfo(domain) {
  try {
    const mapping = loadApiMapping();
    if (!mapping) {
      throw new Error('Không thể load API mapping configuration');
    }

    const normalizedDomain = normalizeDomain(domain);
    
    if (mapping.api_mapping[normalizedDomain]) {
      return mapping.api_mapping[normalizedDomain];
    }

    const subdomainMatch = findSubdomainMatch(normalizedDomain, mapping.api_mapping);
    if (subdomainMatch) {
      return mapping.api_mapping[subdomainMatch];
    }

    // Không tìm thấy mapping - trả về lỗi
    const errorMsg = `Không tìm thấy environment info cho domain: ${normalizedDomain}`;
    console.error('❌', errorMsg);
    throw new Error(errorMsg);

  } catch (error) {
    console.error('❌ Lỗi khi get environment info:', error);
    throw error; // Re-throw error thay vì return null
  }
}

// Update API mapping dynamically
function updateApiMapping(newMapping) {
  try {
    const mappingPath = path.join(__dirname, '../config/api-mapping.json');
    const currentMapping = loadApiMapping();
    
    // Merge with existing mapping
    const updatedMapping = {
      ...currentMapping,
      api_mapping: {
        ...currentMapping.api_mapping,
        ...newMapping
      }
    };

    // Write back to file
    fs.writeFileSync(mappingPath, JSON.stringify(updatedMapping, null, 2));
    console.log('✅ Đã cập nhật API mapping');
    return true;

  } catch (error) {
    console.error('❌ Lỗi khi update API mapping:', error);
    return false;
  }
}

// Get all available domains
function getAllDomains() {
  try {
    const mapping = loadApiMapping();
    if (!mapping) return [];

    return Object.keys(mapping.api_mapping).map(domain => ({
      domain: domain,
      ...mapping.api_mapping[domain]
    }));

  } catch (error) {
    console.error('❌ Lỗi khi get all domains:', error);
    return [];
  }
}

// Validate API server connectivity
async function validateApiServer(apiServer) {
  try {
    const fetch = require('node-fetch');
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 5000); // 5s timeout

    const response = await fetch(`${apiServer}/health`, {
      method: 'GET',
      signal: controller.signal
    });

    clearTimeout(timeoutId);

    return {
      valid: response.ok,
      status: response.status,
      statusText: response.statusText
    };

  } catch (error) {
    return {
      valid: false,
      error: error.message
    };
  }
}

module.exports = {
  loadApiMapping,
  getApiServerByDomain,
  getEnvironmentInfo,
  updateApiMapping,
  getAllDomains,
  validateApiServer,
  normalizeDomain
};
