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

export async function sendEmailViaSMTP({ sender_id, recipient_email, cc = [], bcc = [], subject, body, htmlBody, attachments = [], debug = true }) {
  try {
    console.log("=== sendEmailViaSMTP: START ===");

    const htmlContent = htmlBody || body;

    const missingFields = [];
    if (!sender_id) missingFields.push('sender_id');
    if (!recipient_email || (Array.isArray(recipient_email) && recipient_email.length === 0)) missingFields.push('recipient_email');
    if (!subject) missingFields.push('subject');
    if (!htmlContent) missingFields.push('body/html');

    if (missingFields.length > 0) {
      const errorMsg = `Preflight Validation Failed. Missing required fields: ${missingFields.join(', ')}`;
      console.error(errorMsg);
      return { success: false, error: errorMsg };
    }

    const { data: sessionData } = await supabase.auth.getSession();
    const token = sessionData?.session?.access_token;
    const userId = sessionData?.session?.user?.id;

    const headers = token ? { Authorization: `Bearer ${token}` } : {};

    const formattedAttachments = attachments.map((att) => ({
      filename: att.name || att.filename,
      path: att.url || att.path,
      content: att.content,
    }));

    const recipient = Array.isArray(recipient_email) ? recipient_email : [recipient_email];

    const payload = {
      sender_id,
      recipient,
      cc: Array.isArray(cc) ? cc : [],
      bcc: Array.isArray(bcc) ? bcc : [],
      subject,
      body: htmlContent,
      html: htmlContent,
      attachments: formattedAttachments,
      debug,
      fallback_user_id: userId,
      feature_type: 'smtp_email',
    };

    console.log("Invoking 'send-smtp-email' with payload:", JSON.stringify({
      ...payload,
      attachments: formattedAttachments.map(({ filename, path }) => ({ filename, path })),
    }, null, 2));

    const { data: result, error: fnError } = await supabase.functions.invoke('send-smtp-email', {
      body: payload,
      headers,
    });

    if (fnError) {
      console.error(`Edge Function Error: ${fnError.message}`);
      return { success: false, error: `Edge Function Error: ${fnError.message}` };
    }

    if (result && !result.success) {
      console.error(`Email Sending Failed: ${result.error}`);
      return { success: false, error: result.error || 'Failed to send email.' };
    }

    return {
      success: true,
      status: result?.status || 'accepted',
      history_recorded: result?.history_recorded,
      smtp_response: result?.smtp_response,
      diagnostic_logs: result?.diagnostic_logs,
    };
  } catch (error) {
    console.error("sendEmailViaSMTP caught an error:", error);

    try {
      const authData = await supabase.auth.getUser();
      const userId = authData?.data?.user?.id;
      if (userId) {
        await supabase.from('email_history').insert({
          user_id: userId,
          sender_email: 'unknown',
          recipient_email: typeof recipient_email === 'string' ? recipient_email : JSON.stringify(recipient_email),
          subject,
          body_text: body || htmlBody,
          sent_at: new Date().toISOString(),
          status: 'failed',
          feature_type: 'smtp_email',
          email_headers: { error: error.message },
        });
      }
    } catch (fallbackError) {
      console.error("Failed to log fallback error to history:", fallbackError);
    }

    return { success: false, error: error.message };
  }
}
