import apiClient from './api';

/**
 * Service for managing email templates
 */
const emailTemplateService = {
  /**
   * Get all email templates
   * @returns {Promise<Array>} Array of email templates
   */
  getAllTemplates: async () => {
    try {
      const response = await apiClient.get('/admin/settings/category/email_templates');
      
      // Transform settings into template objects
      return response.data.map(setting => {
        try {
          // Parse the template data from the JSON value
          const templateData = JSON.parse(setting.value);
          return {
            id: setting.key,
            ...templateData
          };
        } catch (e) {
          console.error(`Failed to parse template setting: ${setting.key}`, e);
          return null;
        }
      }).filter(Boolean); // Remove any null entries
    } catch (error) {
      throw error.response?.data || { message: 'Failed to fetch email templates' };
    }
  },

  /**
   * Get a specific email template by ID
   * @param {string} id - Template ID
   * @returns {Promise<Object>} Email template object
   */
  getTemplateById: async (id) => {
    try {
      const response = await apiClient.get(`/admin/settings/${id}`);
      
      // Parse the template data from the JSON value
      const templateData = JSON.parse(response.data.value);
      return {
        id: response.data.key,
        ...templateData
      };
    } catch (error) {
      throw error.response?.data || { message: 'Failed to fetch email template' };
    }
  },

  /**
   * Get templates by type
   * @param {string} type - Template type (e.g., 'login_code', 'shipping_notification')
   * @returns {Promise<Array>} Array of email templates of the specified type
   */
  getTemplatesByType: async (type) => {
    try {
      const templates = await emailTemplateService.getAllTemplates();
      return templates.filter(template => template.type === type);
    } catch (error) {
      throw error;
    }
  },

  /**
   * Get the default template for a specific type
   * @param {string} type - Template type
   * @returns {Promise<Object|null>} Default email template for the type, or null if none exists
   */
  getDefaultTemplate: async (type) => {
    try {
      const templates = await emailTemplateService.getTemplatesByType(type);
      return templates.find(template => template.isDefault) || null;
    } catch (error) {
      throw error;
    }
  },

  /**
   * Create a new email template
   * @param {Object} templateData - Template data
   * @param {string} templateData.name - Template name
   * @param {string} templateData.type - Template type
   * @param {string} templateData.subject - Email subject line
   * @param {string} templateData.content - HTML content of the email template
   * @returns {Promise<Object>} Created email template
   */
  createTemplate: async (templateData) => {
    try {
      // Generate a unique key for the setting
      const templateKey = `email_template_${Date.now()}`;
      
      // Create the template object
      const template = {
        name: templateData.name,
        type: templateData.type,
        subject: templateData.subject,
        content: templateData.content,
        isDefault: templateData.isDefault || false,
        createdAt: new Date().toISOString()
      };
      
      // Save to settings
      const response = await apiClient.put(`/admin/settings/${templateKey}`, {
        value: JSON.stringify(template),
        category: 'email_templates'
      });
      
      return {
        id: templateKey,
        ...template
      };
    } catch (error) {
      throw error.response?.data || { message: 'Failed to create email template' };
    }
  },

  /**
   * Update an existing email template
   * @param {string} id - Template ID
   * @param {Object} templateData - Updated template data
   * @returns {Promise<Object>} Updated email template
   */
  updateTemplate: async (id, templateData) => {
    try {
      // Create the updated template object
      const template = {
        name: templateData.name,
        type: templateData.type,
        subject: templateData.subject,
        content: templateData.content,
        isDefault: templateData.isDefault || false,
        createdAt: templateData.createdAt,
        updatedAt: new Date().toISOString()
      };
      
      // Update in settings
      await apiClient.put(`/admin/settings/${id}`, {
        value: JSON.stringify(template),
        category: 'email_templates'
      });
      
      return {
        id,
        ...template
      };
    } catch (error) {
      throw error.response?.data || { message: 'Failed to update email template' };
    }
  },

  /**
   * Delete an email template
   * @param {string} id - Template ID
   * @returns {Promise<boolean>} Success status
   */
  deleteTemplate: async (id) => {
    try {
      await apiClient.delete(`/admin/settings/${id}`);
      return true;
    } catch (error) {
      throw error.response?.data || { message: 'Failed to delete email template' };
    }
  },

  /**
   * Set a template as the default for its type
   * @param {string} id - Template ID
   * @returns {Promise<Object>} Updated template
   */
  setAsDefault: async (id) => {
    try {
      // Get the template to set as default
      const template = await emailTemplateService.getTemplateById(id);
      
      // Get all templates of the same type
      const typeTemplates = await emailTemplateService.getTemplatesByType(template.type);
      
      // For each template of the same type, unset default if it's set
      for (const t of typeTemplates) {
        if (t.id !== id && t.isDefault) {
          await emailTemplateService.updateTemplate(t.id, {
            ...t,
            isDefault: false
          });
        }
      }
      
      // Set the selected template as default
      return await emailTemplateService.updateTemplate(id, {
        ...template,
        isDefault: true
      });
    } catch (error) {
      throw error.response?.data || { message: 'Failed to set template as default' };
    }
  }
};

export default emailTemplateService;