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

/**
 * Queues an email notification.
 * 
 * @param {string} type - 'incident_report', 'status_update', etc.
 * @param {string[]} recipients - Array of email strings
 * @param {object} data - Data object specific to the notification type
 */
export async function sendEmailNotification(type, recipients, data) {
  try {
    if (!recipients || !Array.isArray(recipients) || recipients.length === 0) {
      console.warn('sendEmailNotification called with no recipients');
      return { success: false, error: 'No recipients provided' };
    }

    const validRecipients = recipients.filter(email => 
      email && typeof email === 'string' && email.trim() !== ''
    );

    if (validRecipients.length === 0) return { success: false, error: 'No valid recipients' };

    console.log(`Sending ${type} email to`, validRecipients);
    
    // Construct email content based on type
    const subject = data.title ? `[${type}] ${data.title}` : `Notification: ${type}`;
    let body = `<h3>${type} Notification</h3><pre>${JSON.stringify(data, null, 2)}</pre>`;
    
    if (type === 'status_update') {
        body = `<h3>Status Update: ${data.title}</h3><p>${data.content || ''}</p><br/>Action: ${data.action || 'None'}`;
    } else if (type === 'incident_report') {
        body = `
          <h3>Incident Report</h3>
          <p><strong>Association:</strong> ${data.associationName}</p>
          <p><strong>Date:</strong> ${data.incidentDate}</p>
          <p><strong>Type:</strong> ${data.type}</p>
          <p><strong>Location:</strong> ${data.location}</p>
          <p><strong>Description:</strong> ${data.description}</p>
        `;
    }

    // Invoke edge function for sending email
    const { data: result, error } = await supabase.functions.invoke('send-notification', {
      body: {
        recipients: validRecipients,
        subject,
        html_body: body,
        metadata: data
      }
    });

    if (error) {
      console.error('Edge function error:', error);
      return { success: false, error: error.message };
    }

    return { success: true, data: result };

  } catch (error) {
    console.error('Failed to send notification:', error);
    return { success: false, error };
  }
}

/**
 * Sends notifications to property owners.
 * 
 * @param {string} associationId - The ID of the association
 * @param {string} title - Email subject
 * @param {string} message - Email body (HTML or text)
 * @param {string} recipientListType - 'all' or filtered
 * @returns {Promise<{success: boolean, count: number, error?: string}>}
 */
export async function sendOwnerNotification(associationId, title, message, recipientListType = 'all') {
  try {
    const { data: owners, error: fetchError } = await supabase
      .from('owners')
      .select('email, first_name, last_name')
      .eq('association_id', associationId)
      .neq('status', 'archived')
      .not('email', 'is', null)
      .neq('email', '');

    if (fetchError) throw fetchError;
    if (!owners || owners.length === 0) {
      return { success: false, error: 'No recipients found matching criteria.' };
    }

    const recipients = [...new Set(owners.map(o => o.email))];

    const { data: result, error } = await supabase.functions.invoke('send-notification', {
      body: {
        recipients,
        subject: title,
        html_body: message,
        metadata: { associationId, recipientListType }
      }
    });

    if (error) {
      return { success: false, count: 0, error: error.message };
    }

    return { 
        success: true, 
        count: recipients.length
    };

  } catch (error) {
    console.error("Error in sendOwnerNotification:", error);
    return { success: false, error: error.message };
  }
}

/**
 * Constructs a formatted email string for association inbound emails.
 * 
 * @param {string} associationName - The name of the association
 * @returns {string} Formatted email string or placeholder
 */
export function constructAssociationInboundEmail(associationName) {
  if (!associationName) return '';
  const sanitizedName = associationName.toLowerCase().replace(/[^a-z0-9]/g, '');
  return `support+${sanitizedName}@example.com`; 
}
