import { supabase } from '@/integrations/supabase/client';

/**
 * Letter Template Utilities
 * Handles all letter template CRUD operations with proper error handling
 */

export const validateTemplateData = (template) => {
  const errors = [];
  
  if (!template.name || template.name.trim().length < 3) {
    errors.push('Template name must be at least 3 characters long');
  }
  
  if (!template.content || template.content.trim().length === 0) {
    errors.push('Template content cannot be empty');
  }
  
  if (template.content && !template.content.includes('<p>') && !template.content.includes('<div>')) {
    errors.push('Template content must contain valid paragraph structure');
  }
  
  return errors;
};

export const fetchAllTemplates = async () => {
  try {
    const { data, error } = await supabase
      .from('letter_templates')
      .select('*')
      .order('name', { ascending: true });
    
    if (error) throw error;
    
    return { success: true, data: data || [] };
  } catch (error) {
    console.error('Error fetching templates:', error);
    return { success: false, error: error.message };
  }
};

export const fetchTemplateById = async (id) => {
  try {
    const { data, error } = await supabase
      .from('letter_templates')
      .select('*')
      .eq('id', id)
      .single();
    
    if (error) throw error;
    
    return { success: true, data };
  } catch (error) {
    console.error('Error fetching template:', error);
    return { success: false, error: error.message };
  }
};

export const createTemplate = async (templateData) => {
  const errors = validateTemplateData(templateData);
  if (errors.length > 0) {
    return { success: false, errors };
  }
  
  try {
    const payload = {
      name: templateData.name.trim(),
      content: templateData.content,
      user_id: (await supabase.auth.getUser()).data.user?.id
    };
    
    const { data, error } = await supabase
      .from('letter_templates')
      .insert([payload])
      .select()
      .single();
    
    if (error) throw error;
    
    return { success: true, data };
  } catch (error) {
    console.error('Error creating template:', error);
    return { success: false, error: error.message };
  }
};

export const updateTemplate = async (id, templateData) => {
  const errors = validateTemplateData(templateData);
  if (errors.length > 0) {
    return { success: false, errors };
  }
  
  try {
    const payload = {
      name: templateData.name.trim(),
      content: templateData.content,
      updated_at: new Date().toISOString()
    };
    
    const { data, error } = await supabase
      .from('letter_templates')
      .update(payload)
      .eq('id', id)
      .select()
      .single();
    
    if (error) throw error;
    
    return { success: true, data };
  } catch (error) {
    console.error('Error updating template:', error);
    return { success: false, error: error.message };
  }
};

export const deleteTemplate = async (id) => {
  try {
    const { error } = await supabase
      .from('letter_templates')
      .delete()
      .eq('id', id);
    
    if (error) throw error;
    
    return { success: true };
  } catch (error) {
    console.error('Error deleting template:', error);
    return { success: false, error: error.message };
  }
};

/**
 * Parse template content to ensure proper structure
 * Handles both legacy and new format templates
 */
export const parseTemplateContent = (content) => {
  if (!content) return '';
  
  try {
    if (content.trim().startsWith('{') || content.trim().startsWith('[')) {
      const parsed = JSON.parse(content);
      
      if (Array.isArray(parsed)) {
        return parsed.map(p => p.content || '').join('\n\n');
      }
      
      if (parsed.paragraphs) {
        return parsed.paragraphs.map(p => p.content || '').join('\n\n');
      }
      
      return content;
    }
    
    return content;
  } catch (e) {
    return content;
  }
};
