const axios = require('axios');

class ServiceClient {
  constructor() {
    this.templateManagerUrl = process.env.TEMPLATE_MANAGER_URL || 'http://localhost:8009';
  }

  async getCustomFeatures(status, limit = 50, offset = 0, authToken) {
    try {
      const params = { limit, offset };
      if (status) params.status = status;
      
      const headers = {};
      if (authToken) {
        headers.Authorization = `Bearer ${authToken}`;
      }
      
      const response = await axios.get(`${this.templateManagerUrl}/api/admin/custom-features`, {
        params,
        headers,
        timeout: 5000
      });
      
      return response.data;
    } catch (error) {
      console.error('Failed to fetch custom features from template-manager:', error.message);
      throw new Error('Template manager service unavailable');
    }
  }

  async reviewCustomFeature(id, reviewData, authToken) {
    try {
      const headers = {};
      if (authToken) {
        headers.Authorization = `Bearer ${authToken}`;
      }
      
      const response = await axios.post(
        `${this.templateManagerUrl}/api/admin/custom-features/${id}/review`,
        reviewData,
        { headers, timeout: 5000 }
      );
      
      return response.data;
    } catch (error) {
      console.error('Failed to review custom feature:', error.message);
      throw new Error('Template manager service unavailable');
    }
  }

  async getCustomTemplates(status, limit = 50, offset = 0, authToken) {
    try {
      const params = { limit, offset };
      if (status) params.status = status;
      
      const headers = {};
      if (authToken) {
        headers.Authorization = `Bearer ${authToken}`;
      }
      
      const response = await axios.get(`${this.templateManagerUrl}/api/admin/custom-templates`, {
        params,
        headers,
        timeout: 5000
      });
      
      return response.data;
    } catch (error) {
      console.error('Failed to fetch custom templates from template-manager:', error.message);
      throw new Error('Template manager service unavailable');
    }
  }

  async reviewCustomTemplate(id, reviewData, authToken) {
    try {
      const headers = {};
      if (authToken) {
        headers.Authorization = `Bearer ${authToken}`;
      }
      
      const response = await axios.post(
        `${this.templateManagerUrl}/api/admin/custom-templates/${id}/review`,
        reviewData,
        { headers, timeout: 5000 }
      );
      
      return response.data;
    } catch (error) {
      console.error('Failed to review custom template:', error.message);
      throw new Error('Template manager service unavailable');
    }
  }
}

module.exports = new ServiceClient();
