import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'
import nodemailer from 'npm:nodemailer'

Deno.serve(async (req) => {
  // Initialize Supabase client
  const supabase = createClient(
    Deno.env.get('SUPABASE_URL') ?? '',
    Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? ''
  )
  // Create Nodemailer transporter
  const transporter = nodemailer.createTransport({
    host: 'email-smtp.eu-west-1.amazonaws.com', // SES SMTP endpoint
    port: 587,
    secure: false, // true for 465, false for other ports
    auth: {
      user: Deno.env.get('SES_SMTP_USERNAME'),
      pass: Deno.env.get('SES_SMTP_PASSWORD')
    }
  })

  // Function to send email
  async function sendEmail(to: string, subject: string, text: string,html: string,attachments: any[]) {
    const mailOptions = {
      from: "no-reply@simpleflowhub.app",
      to,
      subject,
      text,
      html,
      attachments
    }

    try {
      const info = await transporter.sendMail(mailOptions)
      console.log('Email sent: ' + info.response)
      return { success: true, message: 'Email sent successfully' }
    } catch (error) {
      console.error('Error sending email:', error)
      return { success: false, message: 'Failed to send email' }
    }
  }

  const { data, error } = await supabase
  .from("send_que")
  .select("*")
  .eq("status", 0); // Assuming "status" is the field marking unsent emails

    if (error) {
    console.error("Error fetching unsent emails:", error);
    return [];
    }

    for (const email of data) {
        
        let to = email.recipient;
        let subject = email.subject;
        let text = email.body;

        let attachments = [];
        if (email.attachment) {
            const pieces = email.attachment.split("/");
            const filename = pieces[pieces.length - 1];
            attachments.push({
                filename: filename,  // Change filename as needed
                path: email.attachment, // Attachment URL or local path
            });
        }

        const result = await sendEmail(to, subject, text, text, attachments)

        if(result.success){
            const { error } = await supabase
            .from("send_que")
            .update({"status":1,"result":JSON.stringify(result)})
            .eq("id", email.id);
        
          if (error) {
            console.error(`Error updating email status for ID ${email.id}:`, error);
          }
        }else{
            const { error } = await supabase
            .from("send_que")
            .update({"status":2,"result":JSON.stringify(result)})
            .eq("id", email.id);
        
          if (error) {
            console.error(`Error updating email status for ID ${email.id}:`, error);
          }  
        }
       
    }
    return new Response("OK", {
        headers: { 'Content-Type': 'application/json' }
    })

})