const { taoApiUrl, taoHeaders, KTHC_CONFIG } = require('../config/kthc');

// Make API request with timeout and error handling
async function guiYeuCauApi(url, options = {}) {
  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), KTHC_CONFIG.timeout);
  
  try {
    // Use node-fetch for better Unicode support
    const fetch = require('node-fetch');
    
    console.log('🌐 === CHI TIẾT REQUEST ===');
    console.log('🔗 URL:', url);
    console.log('📋 Method:', options.method);
    console.log('📋 Headers:', JSON.stringify(options.headers, null, 2));
    console.log('📦 Body:', options.body);
    console.log('⏱️ Timeout:', KTHC_CONFIG.timeout, 'ms');
    
         console.log('🔄 Đang gửi fetch request...');
     const response = await fetch(url, {
       ...options,
       signal: controller.signal
     });
     console.log('✅ Fetch request hoàn thành');
    
    clearTimeout(timeoutId);
    
         console.log('📊 === CHI TIẾT RESPONSE ===');
     console.log('📊 Status:', response.status);
     console.log('📊 StatusText:', response.statusText);
     console.log('📊 Headers:', JSON.stringify(Object.fromEntries(response.headers.entries()), null, 2));
     console.log('📊 Response OK:', response.ok);
     console.log('📊 Response Type:', response.type);
     console.log('📊 Response URL:', response.url);
    
    if (!response.ok) {
      const errorText = await response.text();
      console.log('❌ Error Response Body:', errorText);
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }
    
         // Kiểm tra content-type để quyết định cách parse response
     const contentType = response.headers.get('content-type') || '';
     console.log('📋 Content-Type:', contentType);
     console.log('📋 Content-Length:', response.headers.get('content-length'));
     console.log('📋 Response Body Available:', response.body ? 'Có' : 'Không');
    
    let result;
    if (contentType.includes('application/json')) {
      // Parse JSON response
      result = await response.json();
      console.log('✅ Response JSON:', JSON.stringify(result, null, 2));
         } else {
       // Parse text response (có thể rỗng)
       console.log('📋 Đang đọc response text...');
       const responseText = await response.text();
       console.log('📋 Response Text Length:', responseText.length);
       console.log('📋 Response Text (raw):', JSON.stringify(responseText));
       console.log('📋 Response Text (trimmed):', JSON.stringify(responseText.trim()));
       
               if (responseText.trim() === '') {
          // Response rỗng - trả về object thành công
          result = { success: true, message: 'Cập nhật thành công' };
          console.log('✅ Empty response - treating as success');
          console.log('✅ API PUT thành công với response rỗng (điều này là bình thường)');
        } else {
         // Cố gắng parse JSON nếu có thể
         try {
           result = JSON.parse(responseText);
           console.log('✅ Parsed JSON from text:', JSON.stringify(result, null, 2));
         } catch (parseError) {
           console.log('⚠️ JSON parse error:', parseError.message);
           // Nếu không parse được JSON, trả về text
           result = { success: true, message: responseText || 'Cập nhật thành công' };
           console.log('✅ Non-JSON response - treating as success:', responseText);
         }
       }
     }
    
    return result;
     } catch (error) {
     clearTimeout(timeoutId);
     console.log('❌ === ERROR DETAILS ===');
     console.log('❌ Error:', error.message);
     console.log('❌ Error Type:', error.name);
     console.log('❌ Error Stack:', error.stack);
     console.log('❌ Error Cause:', error.cause);
     throw error;
   }
}

// Make GET request
async function guiYeuCauGet(endpoint, params = {}, token) {
  const url = taoApiUrl(endpoint, params);
  const headers = taoHeaders(token);
  
  console.log(`🔗 GET ${endpoint}:`, url);
  
  return guiYeuCauApi(url, {
    method: 'GET',
    headers
  });
}

// Make POST request
async function guiYeuCauPost(endpoint, payload = {}, token) {
  const url = taoApiUrl(endpoint);
  const headers = taoHeaders(token);
  
  console.log(`🔗 POST ${endpoint}:`, url);
  console.log('📦 Payload:', JSON.stringify(payload, null, 2));
  
  // Convert payload to form data for better Unicode support
  const formData = new URLSearchParams();
  Object.keys(payload).forEach(key => {
    formData.append(key, payload[key]);
  });
  
  console.log('📋 === FORM DATA DETAILS ===');
  console.log('📋 Form Data String:', formData.toString());
  console.log('📋 Form Data Entries:');
  for (const [key, value] of formData.entries()) {
    console.log(`  ${key}: ${value} (${typeof value})`);
  }
  
  // Update headers for form data
  headers['Content-Type'] = 'application/x-www-form-urlencoded';
  
  return guiYeuCauApi(url, {
    method: 'POST',
    headers,
    body: formData.toString()
  });
}

// Make POST request with JSON format
async function guiYeuCauPostJson(endpoint, payload = {}, token) {
  const url = taoApiUrl(endpoint);
  const headers = taoHeaders(token);
  
  console.log(`🔗 POST JSON ${endpoint}:`, url);
  console.log('📦 Payload:', JSON.stringify(payload, null, 2));
  
  // Keep JSON format
  headers['Content-Type'] = 'application/json';
  
  return guiYeuCauApi(url, {
    method: 'POST',
    headers,
    body: JSON.stringify(payload)
  });
}

// Make PUT request with form data
async function guiYeuCauPut(endpoint, payload = {}, token) {
  const startTime = Date.now();
  const url = taoApiUrl(endpoint);
  const headers = taoHeaders(token);
  
  console.log(`🔗 PUT ${endpoint}:`, url);
  console.log('📦 Payload:', JSON.stringify(payload, null, 2));
  console.log('🔑 Token:', token ? 'Có token' : 'Không có token');
  
  // Convert payload to form data for PUT requests
  const formData = new URLSearchParams();
  Object.keys(payload).forEach(key => {
    formData.append(key, payload[key]);
  });
  
  console.log('📋 === PUT FORM DATA DETAILS ===');
  console.log('📋 Form Data String:', formData.toString());
  console.log('📋 Form Data Entries:');
  for (const [key, value] of formData.entries()) {
    console.log(`  ${key}: ${value} (${typeof value})`);
  }
  
  // Update headers for form data
  headers['Content-Type'] = 'application/x-www-form-urlencoded';
  
  console.log('📋 === PUT REQUEST DETAILS ===');
  console.log('📋 Method: PUT');
  console.log('📋 URL:', url);
  console.log('📋 Headers:', JSON.stringify(headers, null, 2));
  console.log('📋 Body:', formData.toString());
  console.log('📋 Body Length:', formData.toString().length);
  console.log('📋 Body Encoded:', encodeURIComponent(formData.toString()));
  
  try {
    const result = await guiYeuCauApi(url, {
      method: 'PUT',
      headers,
      body: formData.toString()
    });
    
    const duration = Date.now() - startTime;
    console.log(`✅ === PUT REQUEST THÀNH CÔNG ===`);
    console.log(`⏱️ Thời gian: ${duration}ms`);
    console.log(`📊 Result:`, JSON.stringify(result, null, 2));
    
    return result;
  } catch (error) {
    const duration = Date.now() - startTime;
    console.log(`❌ === PUT REQUEST THẤT BẠI ===`);
    console.log(`⏱️ Thời gian: ${duration}ms`);
    console.log(`❌ Error:`, error.message);
    throw error;
  }
}

// Retry API call with different parameters
async function thuLaiGoiApi(apiCall, retryParams = {}) {
  try {
    return await apiCall();
  } catch (error) {
    console.log('🔄 Thử lại với tham số khác:', retryParams);
    return await apiCall(retryParams);
  }
}

// Format error message
function dinhDangThongBaoLoi(error, context = '') {
  let errorMessage = 'Lỗi không xác định';
  
  if (error.name === 'AbortError') {
    errorMessage = 'API timeout - vượt quá 30 giây';
  } else if ((error.message || '').includes('fetch')) {
    errorMessage = 'Không thể kết nối đến server API';
  } else if ((error.message || '').includes('HTTP')) {
    errorMessage = `Lỗi HTTP: ${error.message}`;
  } else {
    errorMessage = error.message || 'Lỗi không xác định';
  }
  
  return `${context ? context + ': ' : ''}${errorMessage}`;
}

// Validate API response
function kiemTraPhanHoiApi(response, expectedFields = []) {
  if (!response) {
    throw new Error('Response rỗng');
  }
  
  for (const field of expectedFields) {
    if (!response.hasOwnProperty(field)) {
      throw new Error(`Thiếu trường bắt buộc: ${field}`);
    }
  }
  
  return true;
}

// Log API performance
function ghiLogHieuNangApi(startTime, endpoint, success = true) {
  const endTime = Date.now();
  const duration = endTime - startTime;
  
  console.log(`⏱️ ${endpoint}: ${duration}ms ${success ? '✅' : '❌'}`);
  
  return duration;
}

// Update chứng từ field by field
async function capNhatChungTuField(endpoint, key, fieldName, fieldValue, token) {
  const startTime = Date.now();
  
  console.log(`🔄 === CẬP NHẬT CHỨNG TỪ FIELD ===`);
  console.log(`🔑 Key: ${key}`);
  console.log(`📝 Field: ${fieldName}`);
  console.log(`📋 Value: ${fieldValue}`);
  console.log(`🔗 Endpoint: ${endpoint}`);
  console.log(`🔑 Token: ${token ? 'Có token' : 'Không có token'}`);
  
  // Tạo payload với format đúng cho form data
  const payload = {
    key: key.toString(),
    values: JSON.stringify({ [fieldName]: fieldValue })
  };
  
  console.log(`📦 PUT Payload:`, JSON.stringify(payload, null, 2));
  console.log(`📋 Values JSON:`, payload.values);
  console.log(`📋 Values Decoded:`, JSON.parse(payload.values));
  
  try {
    const result = await guiYeuCauPut(endpoint, payload, token);
    
    const duration = Date.now() - startTime;
    console.log(`✅ === CẬP NHẬT THÀNH CÔNG ===`);
    console.log(`⏱️ Thời gian: ${duration}ms`);
    console.log(`📊 Result:`, JSON.stringify(result, null, 2));
    
    return result;
  } catch (error) {
    const duration = Date.now() - startTime;
    console.log(`❌ === CẬP NHẬT THẤT BẠI ===`);
    console.log(`⏱️ Thời gian: ${duration}ms`);
    console.log(`❌ Error:`, error.message);
    throw error;
  }
}

// Test function để kiểm tra PUT API
async function testPutAPI() {
  try {
    console.log('🧪 === TEST PUT API ===');
    
    // Test với một payload đơn giản
    const testPayload = {
      key: '2964',
      values: JSON.stringify({ Ndct: 'Test AI-Chuyển bảo hiểm' })
    };
    
    console.log('📦 Test Payload:', JSON.stringify(testPayload, null, 2));
    
    // Sử dụng token test (cần thay thế bằng token thực)
    const testToken = 'Bearer eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJuYmYiOjE3NTU3OTE0ODksImV4cCI6MTc1ODM4MzQ4OSwiaWF0IjoxNzU1NzkxNDg5LCJpc3MiOiJRTEhEIiwiYXVkIjoiUUxIRCJ9.GYQbIav2mN7IiexrnmoJBS-ekwgPg0dpGNzeKMWUhKKvsteTuWUBHL43L35ZBqR00LJjsKolsMpZsp6uwHlfRA';
    
    const result = await guiYeuCauPut('/ClassSubTaoBhnhoms/Put', testPayload, testToken);
    
    console.log('✅ Test PUT thành công:', JSON.stringify(result, null, 2));
    return result;
  } catch (error) {
    console.error('❌ Test PUT thất bại:', error.message);
    throw error;
  }
}

module.exports = {
  guiYeuCauApi,
  guiYeuCauGet,
  guiYeuCauPost,
  guiYeuCauPostJson,
  guiYeuCauPut,
  capNhatChungTuField,
  thuLaiGoiApi,
  dinhDangThongBaoLoi,
  kiemTraPhanHoiApi,
  ghiLogHieuNangApi,
  testPutAPI
};
