/**
 * email-send-business Edge Function
 *
 * 从草稿箱读取邮件，通过 Dify Workflow API 发送商业邮件（SMTP）
 *
 * 输入参数：
 *   - email_id: 草稿邮件 ID（必填）
 *
 * 处理流程：
 * 1. 从 emails 表读取草稿邮件（status = "draft"）
 * 2. 调用 Dify Workflow API 发送邮件
 * 3. 更新草稿状态为 "sent"，设置 sent_at
 * 4. 如果是回复邮件（有 in_reply_to），更新原邮件状态为 "replied"
 */

import { createClient } from "https://esm.sh/@supabase/supabase-js@2.57.4";

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

interface SendEmailRequest {
  email_id: string;
}

/**
 * 调用 Dify Workflow API 发送邮件
 */
async function sendEmailViaDify(data: {
  email_user: string;
  email_pass: string;
  from_email: string;
  to_emails: string[];
  subject: string;
  body_text: string;
  body_html: string;
  cc_emails: string[];
  bcc_emails: string[];
  attachments: any[];
}): Promise<any> {
  const DIFY_API_KEY = Deno.env.get("DIFY_EMAIL_API_KEY");
  const DIFY_BASE_URL =
    Deno.env.get("DIFY_EMAIL_BASE_URL") ||
    "http://ai.qianjiangcloud.com/v1";

  if (!DIFY_API_KEY) {
    throw new Error("DIFY_EMAIL_API_KEY not configured");
  }

  console.log("🤖 [email-send-business] Calling Dify Workflow API (send)...");

  const response = await fetch(`${DIFY_BASE_URL}/workflows/run`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${DIFY_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      inputs: {
        action: "send",
        data: JSON.stringify(data),
      },
      response_mode: "blocking",
      user: "system",
    }),
  });

  if (!response.ok) {
    const errorText = await response.text();
    console.error(
      "❌ [email-send-business] Dify API error:",
      response.status,
      errorText
    );
    throw new Error(
      `Dify Workflow API error: ${response.status} - ${errorText}`
    );
  }

  const result = await response.json();
  console.log("📤 [email-send-business] Dify response:", {
    workflow_run_id: result.workflow_run_id,
    status: result.data?.status,
    elapsed_time: result.data?.elapsed_time,
  });

  if (result.data?.status === "failed") {
    throw new Error(
      `Dify Workflow failed: ${result.data?.error || "Unknown error"}`
    );
  }

  return result;
}

/**
 * 主入口
 */
Deno.serve(async (req) => {
  if (req.method === "OPTIONS") {
    return new Response(null, { headers: corsHeaders });
  }

  const traceId = req.headers.get("x-trace-id") || crypto.randomUUID();

  try {
    const body: SendEmailRequest = await req.json();

    console.log("📥 [email-send-business] Incoming request:", {
      trace_id: traceId,
      email_id: body.email_id,
    });

    // 参数校验
    if (!body.email_id) {
      return new Response(
        JSON.stringify({ error: "email_id is required" }),
        {
          status: 400,
          headers: { ...corsHeaders, "Content-Type": "application/json" },
        }
      );
    }

    // 初始化 Supabase
    const supabaseUrl = Deno.env.get("SUPABASE_URL")!;
    const supabaseKey = Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!;
    const supabase = createClient(supabaseUrl, supabaseKey);

    // 1. 从数据库读取草稿邮件
    const { data: draft, error: fetchError } = await supabase
      .from("emails")
      .select("*")
      .eq("id", body.email_id)
      .eq("status", "draft")
      .single();

    if (fetchError || !draft) {
      const errorMsg = fetchError
        ? fetchError.message
        : "Draft email not found";
      console.error("❌ [email-send-business] Failed to fetch draft:", errorMsg);
      return new Response(
        JSON.stringify({
          success: false,
          error: errorMsg,
          trace_id: traceId,
        }),
        {
          status: 404,
          headers: { ...corsHeaders, "Content-Type": "application/json" },
        }
      );
    }

    console.log("📄 [email-send-business] Draft loaded:", {
      id: draft.id,
      to: draft.to_email,
      subject: draft.subject?.substring(0, 50),
      in_reply_to: draft.in_reply_to,
    });

    // 2. 读取环境变量
    const EMAIL_USER = Deno.env.get("IMAP_USER");
    const EMAIL_PASS = Deno.env.get("IMAP_PASSWORD");

    if (!EMAIL_USER || !EMAIL_PASS) {
      throw new Error("IMAP_USER or IMAP_PASSWORD not configured");
    }

    // 解析收件人（to_email 可能是逗号分隔的字符串）
    const toEmails = draft.to_email
      ? draft.to_email.split(",").map((e: string) => e.trim()).filter(Boolean)
      : [];

    if (toEmails.length === 0) {
      return new Response(
        JSON.stringify({ error: "No recipients in draft email" }),
        {
          status: 400,
          headers: { ...corsHeaders, "Content-Type": "application/json" },
        }
      );
    }

    // 3. 调用 Dify 发送邮件
    const difyResult = await sendEmailViaDify({
      email_user: EMAIL_USER,
      email_pass: EMAIL_PASS,
      from_email: EMAIL_USER,
      to_emails: toEmails,
      subject: draft.subject || "",
      body_text: draft.body_text || "",
      body_html: draft.body_html || draft.body_text || "",
      cc_emails: draft.cc_emails || [],
      bcc_emails: draft.bcc_emails || [],
      attachments: draft.attachments || [],
    });

    // 4. 更新草稿状态为 sent
    const { error: updateError } = await supabase
      .from("emails")
      .update({
        status: "sent",
        sent_at: new Date().toISOString(),
        metadata: {
          ...(draft.metadata || {}),
          source: "email-send-business",
          workflow_run_id: difyResult.workflow_run_id,
        },
      })
      .eq("id", body.email_id);

    if (updateError) {
      console.warn(
        "⚠️ [email-send-business] Failed to update draft status:",
        updateError.message
      );
    } else {
      console.log("✅ [email-send-business] Draft status updated to sent");
    }

    // 5. 如果是回复邮件，更新原邮件状态为 replied
    if (draft.in_reply_to) {
      const { error: replyUpdateError } = await supabase
        .from("emails")
        .update({ status: "replied" })
        .eq("id", draft.in_reply_to);

      if (replyUpdateError) {
        console.warn(
          "⚠️ [email-send-business] Failed to update original email status:",
          replyUpdateError.message
        );
      } else {
        console.log(
          `✅ [email-send-business] Original email ${draft.in_reply_to} marked as replied`
        );
      }
    }

    // 6. 返回结果
    const result = {
      success: true,
      trace_id: traceId,
      email_id: draft.id,
      workflow_run_id: difyResult.workflow_run_id,
      to_emails: toEmails,
      subject: draft.subject,
    };

    console.log("✅ [email-send-business] Completed:", result);

    return new Response(JSON.stringify(result), {
      status: 200,
      headers: { ...corsHeaders, "Content-Type": "application/json" },
    });
  } catch (error) {
    console.error("❌ [email-send-business] Fatal error:", error);

    return new Response(
      JSON.stringify({
        success: false,
        error: error instanceof Error ? error.message : "Unknown error",
        trace_id: traceId,
      }),
      {
        status: 500,
        headers: { ...corsHeaders, "Content-Type": "application/json" },
      }
    );
  }
});
