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

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

interface SendEmailRequest {
  to: string;
  subject: string;
  body: string;
  contactId?: string;
}

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

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

    // Get authorization header
    const authHeader = req.headers.get("Authorization");
    if (!authHeader) {
      return new Response(JSON.stringify({ error: "Unauthorized" }), {
        status: 401,
        headers: { "Content-Type": "application/json", ...corsHeaders },
      });
    }

    // Verify user
    const token = authHeader.replace("Bearer ", "");
    const { data: { user }, error: userError } = await supabase.auth.getUser(token);
    if (userError || !user) {
      return new Response(JSON.stringify({ error: "Unauthorized" }), {
        status: 401,
        headers: { "Content-Type": "application/json", ...corsHeaders },
      });
    }

    const { to, subject, body, contactId }: SendEmailRequest = await req.json();

    if (!to || !subject || !body) {
      return new Response(JSON.stringify({ error: "Missing required fields: to, subject, body" }), {
        status: 400,
        headers: { "Content-Type": "application/json", ...corsHeaders },
      });
    }

    // Get business and email config
    const { data: business } = await supabase
      .from("business")
      .select("id")
      .limit(1)
      .single();

    if (!business) {
      return new Response(JSON.stringify({ error: "No business configured" }), {
        status: 400,
        headers: { "Content-Type": "application/json", ...corsHeaders },
      });
    }

    const { data: emailConfig } = await supabase
      .from("business_email_config")
      .select("*")
      .eq("business_id", business.id)
      .eq("is_active", true)
      .limit(1)
      .single();

    if (!emailConfig) {
      return new Response(JSON.stringify({ error: "Email not configured or not active. Please configure SMTP settings." }), {
        status: 400,
        headers: { "Content-Type": "application/json", ...corsHeaders },
      });
    }

    // Determine TLS settings
    const useTls = emailConfig.smtp_encryption === "tls" || emailConfig.smtp_encryption === "ssl";

    // Create SMTP client
    const client = new SMTPClient({
      connection: {
        hostname: emailConfig.smtp_host,
        port: emailConfig.smtp_port || 587,
        tls: useTls,
        auth: {
          username: emailConfig.smtp_username,
          password: emailConfig.smtp_password,
        },
      },
    });

    // Send email
    await client.send({
      from: emailConfig.from_email || emailConfig.smtp_username,
      to: to,
      subject: subject,
      content: body,
      html: body.replace(/\n/g, "<br>"),
    });

    await client.close();

    // Log activity
    if (contactId) {
      await supabase.from("activities").insert({
        user_id: user.id,
        contact_id: contactId,
        type: "email",
        direction: "outbound",
        subject: subject,
        body_preview: body.substring(0, 200),
        status: "sent",
        category: "user",
      });
    }

    console.log(`Email sent successfully to ${to}`);

    return new Response(JSON.stringify({ success: true, message: "Email sent successfully" }), {
      status: 200,
      headers: { "Content-Type": "application/json", ...corsHeaders },
    });
  } catch (error: any) {
    console.error("Error sending email:", error);
    return new Response(JSON.stringify({ success: false, error: error.message }), {
      status: 500,
      headers: { "Content-Type": "application/json", ...corsHeaders },
    });
  }
});
