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

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

const logStep = (step: string, details?: Record<string, unknown>) => {
  const detailsStr = details ? ` - ${JSON.stringify(details)}` : "";
  console.log(`[SEND-EMAIL] ${step}${detailsStr}`);
};

interface EmailRequest {
  to: string;
  templateName: string;
  variables?: Record<string, string>;
}

const replaceVariables = (
  template: string,
  variables: Record<string, string>
): string => {
  let result = template;
  for (const [key, value] of Object.entries(variables)) {
    const regex = new RegExp(`{{${key}}}`, "g");
    result = result.replace(regex, value);
  }
  return result;
};

// Send email using Resend API directly
async function sendEmailWithResend(
  apiKey: string,
  to: string,
  subject: string,
  htmlContent: string,
  textContent?: string
) {
  const response = await fetch("https://api.resend.com/emails", {
    method: "POST",
    headers: {
      "Authorization": `Bearer ${apiKey}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      from: "AppForge <noreply@appforge.dev>",
      to: [to],
      subject,
      html: htmlContent,
      text: textContent,
    }),
  });

  if (!response.ok) {
    const error = await response.text();
    throw new Error(`Resend API error: ${error}`);
  }

  return await response.json();
}

// Resolve the Resend API key: env var first, then system_settings DB fallback
async function resolveResendApiKey(supabaseUrl: string, serviceRoleKey: string): Promise<string | null> {
  const envKey = Deno.env.get("RESEND_API_KEY");
  if (envKey) return envKey;

  try {
    const supabase = createClient(supabaseUrl, serviceRoleKey);
    const { data } = await supabase
      .from("system_settings")
      .select("value")
      .eq("key", "resend_api_key")
      .maybeSingle();

    if (data?.value) {
      const raw = data.value;
      if (typeof raw === "string" && raw.trim().length > 0) return raw.trim();
      // Handle JSON-wrapped string
      if (typeof raw === "object" && raw !== null) {
        const str = JSON.stringify(raw).replace(/^"|"$/g, "");
        if (str.trim().length > 0) return str.trim();
      }
    }
  } catch (err) {
    logStep("Failed to fetch resend_api_key from system_settings", { error: String(err) });
  }

  return null;
}

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

  const supabaseUrl = Deno.env.get("SUPABASE_URL")!;
  const serviceRoleKey = Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!;

  // Health check endpoint
  const url = new URL(req.url);
  if (url.searchParams.get("health") === "1" || req.method === "GET") {
    const resendApiKey = await resolveResendApiKey(supabaseUrl, serviceRoleKey);
    return new Response(
      JSON.stringify({
        status: "ok",
        function: "send-email",
        timestamp: new Date().toISOString(),
        env: {
          RESEND_API_KEY: !!resendApiKey,
          SUPABASE_URL: !!supabaseUrl,
          SUPABASE_SERVICE_ROLE_KEY: !!serviceRoleKey,
        },
      }),
      { status: 200, headers: { ...corsHeaders, "Content-Type": "application/json" } }
    );
  }

  try {
    const resendApiKey = await resolveResendApiKey(supabaseUrl, serviceRoleKey);
    if (!resendApiKey) {
      logStep("RESEND_API_KEY not configured (env or DB) - skipping email");
      return new Response(
        JSON.stringify({ success: false, message: "Email service not configured. Set the Resend API key in Admin → Settings → Notifications." }),
        {
          status: 200,
          headers: { ...corsHeaders, "Content-Type": "application/json" },
        }
      );
    }

    const supabase = createClient(supabaseUrl, serviceRoleKey);

    const { to, templateName, variables = {} }: EmailRequest = await req.json();

    if (!to || !templateName) {
      throw new Error("Missing required fields: to, templateName");
    }

    logStep("Fetching email template", { templateName });

    // Fetch the email template
    const { data: template, error: templateError } = await supabase
      .from("email_templates")
      .select("*")
      .eq("name", templateName)
      .eq("is_active", true)
      .single();

    if (templateError || !template) {
      logStep("Template not found or inactive", { templateName, error: templateError?.message });
      return new Response(
        JSON.stringify({ success: false, message: "Email template not found" }),
        {
          status: 200,
          headers: { ...corsHeaders, "Content-Type": "application/json" },
        }
      );
    }

    // Replace variables in subject and content
    const subject = replaceVariables(template.subject, variables);
    const htmlContent = replaceVariables(template.html_content, variables);
    const textContent = template.text_content
      ? replaceVariables(template.text_content, variables)
      : undefined;

    logStep("Sending email", { to, subject });

    // Send the email
    const emailResponse = await sendEmailWithResend(
      resendApiKey,
      to,
      subject,
      htmlContent,
      textContent
    );

    logStep("Email sent successfully", { emailId: emailResponse.id });

    return new Response(
      JSON.stringify({ success: true, emailId: emailResponse.id }),
      {
        status: 200,
        headers: { ...corsHeaders, "Content-Type": "application/json" },
      }
    );
  } catch (error: unknown) {
    const message = error instanceof Error ? error.message : "Unknown error";
    logStep("Error sending email", { error: message });
    return new Response(
      JSON.stringify({ success: false, error: message }),
      {
        status: 500,
        headers: { ...corsHeaders, "Content-Type": "application/json" },
      }
    );
  }
});
