import { serve } from "https://deno.land/std@0.168.0/http/server.ts"
import nodemailer from "npm:nodemailer"

const corsHeaders = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
}

serve(async (req) => {
  // Handle CORS Preflight
  if (req.method === 'OPTIONS') {
    return new Response('ok', { headers: corsHeaders })
  }

  try {
    const { to_email, subject, html_content } = await req.json()

    const transporter = nodemailer.createTransport({
      host: "mail.privateemail.com",
      port: 465,
      secure: true, 
      pool: true,
      logger: true,
      debug: true,
      auth: {
        user: "info@baytownnetworkingprofessionals.com",
        pass: "C^S3v%WC0Vdi",
      },
      connectionTimeout: 10000,
    })

    // The Jumper Wire fallback logic
    const finalRecipient = to_email || "info@baytownnetworkingprofessionals.com"
    const finalSubject = subject || "Sunbelt Test - Manual Override"
    const finalHtml = html_content || "<h1>System Check</h1><p>The Cloud-to-Namecheap connection is active.</p>"

    const info = await transporter.sendMail({
      from: '"Sunbelt Metrics" <info@baytownnetworkingprofessionals.com>',
      to: finalRecipient,
      subject: finalSubject,
      html: finalHtml,
    })

    console.log("Email sent successfully:", info.messageId)

    return new Response(
      JSON.stringify({ success: true, messageId: info.messageId }),
      { headers: { ...corsHeaders, 'Content-Type': 'application/json' }, status: 200 }
    )

  } catch (error: any) {
    console.error("Error in function:", error.message)
    return new Response(
      JSON.stringify({ success: false, error: error.message }),
      { headers: { ...corsHeaders, 'Content-Type': 'application/json' }, status: 200 }
    )
  }
})