import { serve } from "https://deno.land/std@0.190.0/http/server.ts";
import { createClient } from "https://esm.sh/@supabase/supabase-js@2";

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

interface TestSmtpRequest {
  business_id: string;
}

serve(async (req) => {
  // Handle CORS preflight
  if (req.method === "OPTIONS") {
    return new Response(null, { headers: corsHeaders });
  }

  try {
    const supabaseUrl = Deno.env.get("SUPABASE_URL")!;
    const supabaseKey = Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!;
    const supabase = createClient(supabaseUrl, supabaseKey);

    // Get authorization header
    const authHeader = req.headers.get("Authorization");
    if (!authHeader) {
      throw new Error("No authorization header");
    }

    // Verify user
    const token = authHeader.replace("Bearer ", "");
    const { data: userData, error: userError } = await supabase.auth.getUser(token);
    if (userError || !userData.user) {
      throw new Error("Unauthorized");
    }

    const { business_id }: TestSmtpRequest = await req.json();

    // Get email config
    const { data: config, error: configError } = await supabase
      .from("business_email_config")
      .select("*")
      .eq("business_id", business_id)
      .single();

    if (configError || !config) {
      throw new Error("Email configuration not found");
    }

    if (!config.smtp_host || !config.smtp_port || !config.smtp_username || !config.smtp_password) {
      throw new Error("SMTP configuration is incomplete");
    }

    // Get user email for test
    const testEmail = config.from_email || userData.user.email;
    if (!testEmail) {
      throw new Error("No email address available for testing");
    }

    // Import SMTP client
    const { SMTPClient } = await import("https://deno.land/x/denomailer@1.6.0/mod.ts");

    // Create SMTP client
    const client = new SMTPClient({
      connection: {
        hostname: config.smtp_host,
        port: config.smtp_port,
        tls: config.smtp_encryption === 'tls',
        auth: {
          username: config.smtp_username,
          password: config.smtp_password,
        },
      },
    });

    // Send test email
    await client.send({
      from: config.from_email || config.smtp_username,
      to: testEmail,
      subject: "SMTP Test - Connection Successful!",
      content: `This is a test email to verify your SMTP configuration is working correctly.

Sent from: ${config.from_name || 'Your CRM'}
SMTP Host: ${config.smtp_host}
Port: ${config.smtp_port}
Encryption: ${config.smtp_encryption}

If you received this email, your email configuration is working properly!`,
    });

    await client.close();

    return new Response(
      JSON.stringify({ 
        success: true, 
        message: `Test email sent successfully to ${testEmail}` 
      }),
      {
        status: 200,
        headers: { "Content-Type": "application/json", ...corsHeaders },
      }
    );
  } catch (error: any) {
    console.error("SMTP test error:", error);
    
    let errorMessage = error.message || "Unknown error occurred";
    
    // Provide more helpful error messages
    if (errorMessage.includes("connect")) {
      errorMessage = "Could not connect to SMTP server. Please verify the host and port.";
    } else if (errorMessage.includes("auth") || errorMessage.includes("535")) {
      errorMessage = "Authentication failed. Please check your username and password.";
    } else if (errorMessage.includes("timeout")) {
      errorMessage = "Connection timed out. Please verify the SMTP server is accessible.";
    }

    return new Response(
      JSON.stringify({ 
        success: false, 
        error: errorMessage 
      }),
      {
        status: 400,
        headers: { "Content-Type": "application/json", ...corsHeaders },
      }
    );
  }
});
