/**
 * fetch-email Edge Function
 *
 * 定时调用 Dify Workflow API 拉取阿里企业邮箱邮件，
 * 自动分类后存入 Supabase emails 表，高优先级邮件触发业务告警。
 *
 * 触发方式：
 *   - pg_cron 定时调用（每 10 分钟）
 *   - 手动 POST 调用
 */ 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"
};
/**
 * 调用 Dify Workflow API 拉取邮件
 */ async function fetchEmailsFromDify(limit = 2) {
  const DIFY_API_KEY = Deno.env.get("DIFY_EMAIL_API_KEY");
  const DIFY_BASE_URL = Deno.env.get("DIFY_BASE_URL");
  const EMAIL_USER = Deno.env.get("IMAP_USER");
  const EMAIL_PASS = Deno.env.get("IMAP_PASSWORD");
  if (!DIFY_API_KEY) {
    throw new Error("DIFY_EMAIL_API_KEY not configured");
  }
  if (!EMAIL_USER || !EMAIL_PASS) {
    throw new Error("IMAP_USER or IMAP_PASSWORD not configured");
  }
  const apiUrl = `${DIFY_BASE_URL}/workflows/run`;
  const requestBody = {
    inputs: {
      action: "fetch",
      data: JSON.stringify({
        email_user: EMAIL_USER,
        email_pass: EMAIL_PASS,
        limit: String(limit),
      }),
    },
    response_mode: "blocking",
    user: "system",
  };

  console.log("🤖 [email-fetch] Calling Dify Workflow API...", {
    url: apiUrl,
    key_prefix: DIFY_API_KEY.substring(0, 8) + "...",
    email_user: EMAIL_USER,
    limit,
    body: JSON.stringify(requestBody),
  });

  const response = await fetch(apiUrl, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${DIFY_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify(requestBody),
  });

  console.log("📡 [email-fetch] Dify API response:", {
    status: response.status,
    statusText: response.statusText,
    headers: Object.fromEntries(response.headers.entries()),
  });

  if (!response.ok) {
    const errorText = await response.text();
    console.error("❌ [email-fetch] Dify API error:", {
      status: response.status,
      body: errorText.substring(0, 500),
    });
    throw new Error(`Dify Workflow API error: ${response.status} - ${errorText}`);
  }
  const result = await response.json();
  console.log("📥 [email-fetch] Dify response:", {
    workflow_run_id: result.workflow_run_id,
    status: result.data?.status,
    email_count: result.data?.outputs?.emails?.length || 0,
    elapsed_time: result.data?.elapsed_time
  });
  if (result.data?.status === "failed") {
    throw new Error(`Dify Workflow failed: ${result.data?.error || "Unknown error"}`);
  }
  return result.data?.outputs?.emails || [];
}
/**
 * 自动分类邮件（基于关键词规则）
 */ function categorizeEmail(subject, body) {
  const text = `${subject} ${body}`.toLowerCase();
  // 优先级：异常 > 支付 > 收货 > 下单 > 履约 > 咨询 > 日常
  if (/退货|退款|质量问题|投诉|异常|破损/.test(text)) return "abnormal_order";
  if (/付款|到账|发票|汇款|对账|账期/.test(text)) return "payment_notification";
  if (/收货|签收|物流跟踪|快递|运单/.test(text)) return "delivery_receipt";
  if (/下单|采购订单|订购|合同确认/.test(text)) return "order_placed";
  if (/发货|备货|生产进度|交期/.test(text)) return "order_fulfillment";
  if (/询价|询盘|报价|产品咨询|样品|规格/.test(text)) return "product_inquiry";
  if (/节日快乐|新年|恭喜|祝商祺/.test(text)) return "daily_greetings";
  return "product_inquiry"; // 默认分类
}
/**
 * 缓存系统默认用户 ID（避免每次查询）
 */ let cachedDefaultUserId = null;
/**
 * 查找邮箱对应的用户 ID
 * 通过 RPC 调用 auth 层的用户查找（需要数据库函数支持）
 * 找不到则回退到第一个系统用户
 */ async function lookupUserId(supabase, emailAddress) {
  // 方式 1：通过 RPC 查找 auth.users（需要数据库中有此函数）
  const { data: rpcResult } = await supabase.rpc("get_user_id_by_email", {
    email_address: emailAddress
  }).maybeSingle();
  if (rpcResult) {
    console.log(`✅ [email-fetch] Found user via RPC: ${rpcResult}`);
    return rpcResult;
  }
  // 方式 2：使用缓存的系统默认用户
  if (cachedDefaultUserId) return cachedDefaultUserId;
  // 查找第一个用户作为默认收件人
  const { data: defaultUser } = await supabase.from("profiles").select("user_id").order("created_at", {
    ascending: true
  }).limit(1).maybeSingle();
  if (defaultUser?.user_id) {
    cachedDefaultUserId = defaultUser.user_id;
    console.log(`⚠️ [email-fetch] No user for ${emailAddress}, using default: ${cachedDefaultUserId}`);
    return cachedDefaultUserId;
  }
  console.error(`❌ [email-fetch] No users exist in system`);
  return null;
}
/**
 * 将 Dify 返回的邮件 status 映射到数据库允许的 status
 * DB CHECK: draft / sending / sent / delivered / read / failed
 */ function mapEmailStatus(difyStatus) {
  const statusMap = {
    delivered: "delivered",
    sent: "sent",
    read: "read",
    failed: "failed",
    draft: "draft",
    sending: "sending"
  };
  return statusMap[difyStatus?.toLowerCase()] || "delivered";
}
/**
 * 存入数据库（带去重）
 * 完全对齐 emails 表实际结构
 */ async function saveEmailToDatabase(supabase, email, category) {
  // 检查是否已存在（按 message_id 去重）
  if (email.message_id) {
    const { data: existing } = await supabase.from("emails").select("id").eq("message_id", email.message_id).maybeSingle();
    if (existing) {
      console.log(`⚠️ [email-fetch] Duplicate email: ${email.message_id}`);
      return {
        id: existing.id,
        isDuplicate: true
      };
    }
  }
  // 查找收件人对应的 user_id
  const userId = await lookupUserId(supabase, email.to_email);
  if (!userId) {
    console.warn(`⚠️ [email-fetch] Skipping email: no user for ${email.to_email}`);
    return {
      id: '',
      isDuplicate: true
    };
  }
  // 构建邮件记录 — 严格对齐表结构
  const emailRecord = {
    // === 必填字段 ===
    user_id: userId,
    from_email: email.from_email,
    to_email: email.to_email,
    subject: email.subject || "(无主题)",
    status: mapEmailStatus(email.status),
    // === 正文（两个独立字段） ===
    body_html: email.body_html || null,
    body_text: email.body_text || null,
    // === 抄送/密送（text[] 数组类型） ===
    cc_emails: email.cc_emails || [],
    bcc_emails: email.bcc_emails || [],
    // === 时间戳 ===
    sent_at: email.sent_at || null,
    delivered_at: email.delivered_at || null,
    read_at: email.read_at || null,
    failed_at: email.failed_at || null,
    failure_reason: email.failure_reason || null,
    // === 邮件标识 ===
    message_id: email.message_id || null,
    thread_id: email.thread_id || null,
    reply_to_message_id: email.reply_to_message_id || null,
    in_reply_to: email.reply_to_message_id || null,
    // === 附件 ===
    attachments: email.attachments || [],
    has_attachments: (email.attachments?.length || 0) > 0,
    // === IMAP 相关 ===
    imap_uid: email.metadata?.imap_uid ? parseInt(email.metadata.imap_uid) : null,
    // === 元数据（存储分类等扩展信息） ===
    metadata: {
      ...email.metadata || {},
      category: category,
      source: "dify_imap"
    },
    // === cc 冗余字段（兼容旧代码） ===
    cc: email.cc_emails?.join(", ") || null
  };
  const { data, error } = await supabase.from("emails").insert(emailRecord).select("id").single();
  if (error) {
    console.error("❌ [email-fetch] Insert error:", error.message);
    throw new Error(`Database insert error: ${error.message}`);
  }
  console.log(`✅ [email-fetch] Saved email: id=${data.id}, category=${category}`);
  return {
    id: data.id,
    isDuplicate: false
  };
}
/**
 * 触发业务动作（高优先级邮件创建告警）
 */ async function triggerBusinessAction(supabase, email, category, emailId) {
  const highPriority = [
    "abnormal_order",
    "payment_notification"
  ];
  const mediumPriority = [
    "order_placed"
  ];
  let severity = null;
  if (highPriority.includes(category)) {
    severity = "high";
  } else if (mediumPriority.includes(category)) {
    severity = "medium";
  }
  if (!severity) return;
  const categoryLabels = {
    abnormal_order: "异常订单",
    payment_notification: "支付通知",
    order_placed: "新订单"
  };
  const alertTitle = `📧 ${categoryLabels[category] || category}：${email.subject || "(无主题)"}`;
  const alertMessage = [
    `来自: ${email.from_email}`,
    `发送至: ${email.to_email}`,
    `时间: ${email.sent_at}`,
    email.body_text ? `摘要: ${email.body_text.slice(0, 200)}...` : ""
  ].filter(Boolean).join("\n");
  console.log(`🚨 [email-fetch] Creating alert: ${severity} - ${alertTitle}`);
  try {
    await supabase.from("business_alerts").insert({
      title: alertTitle,
      message: alertMessage,
      severity,
      source: "email",
      source_id: emailId,
      category,
      status: "unread",
      created_at: new Date().toISOString()
    });
    console.log("✅ [email-fetch] Alert created");
  } catch (e) {
    console.warn("⚠️ [email-fetch] Failed to create alert:", e);
  }
}
/**
 * 更新同步状态
 */ async function updateSyncState(supabase, successCount, duplicateCount, error) {
  try {
    await supabase.from("email_sync_state").update({
      last_synced_at: new Date().toISOString(),
      total_synced: successCount,
      last_error: error
    }).eq("id", 1);
  } catch (e) {
    console.warn("⚠️ [email-fetch] Failed to update sync state:", e);
  }
}
/**
 * 主入口
 */ 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 {
    console.log("📥 [email-fetch] Starting email fetch...", {
      trace_id: traceId
    });
    // 解析请求参数
    let limit = 2;
    try {
      const body = await req.json();
      limit = body.limit || 2;
    } catch  {
    // 允许空 body
    }
    // 初始化 Supabase
    const supabaseUrl = Deno.env.get("SUPABASE_URL");
    const supabaseKey = Deno.env.get("SUPABASE_SERVICE_ROLE_KEY");
    const supabase = createClient(supabaseUrl, supabaseKey);
    // 1. 调用 Dify 拉取邮件
    const emails = await fetchEmailsFromDify(limit);
    console.log(`📬 [email-fetch] Fetched ${emails.length} emails`);
    // 2. 逐封处理
    let successCount = 0;
    let duplicateCount = 0;
    let skippedCount = 0;
    const results = [];
    const errors = [];
    const skipped = [];
    for (const email of emails){
      try {
        // 自动分类
        const category = categorizeEmail(email.subject, email.body_text);
        console.log(`🏷️ [email-fetch] Categorized: ${email.subject} → ${category}`);
        // 查找用户 ID
        const userId = await lookupUserId(supabase, email.to_email);
        if (!userId) {
          skippedCount++;
          skipped.push({
            subject: email.subject,
            from: email.from_email,
            reason: `No user found for ${email.to_email}`
          });
          console.warn(`⚠️ [email-fetch] Skipping email: no user for ${email.to_email}`);
          continue;
        }
        // 检查重复
        if (email.message_id) {
          const { data: existing } = await supabase.from("emails").select("id").eq("message_id", email.message_id).maybeSingle();
          if (existing) {
            duplicateCount++;
            results.push({
              email_id: existing.id,
              from: email.from_email,
              subject: email.subject,
              category,
              is_duplicate: true
            });
            console.log(`⚠️ [email-fetch] Duplicate email: ${email.message_id}`);
            continue;
          }
        }
        // 构建邮件记录
        const emailRecord = {
          user_id: userId,
          from_email: email.from_email,
          to_email: email.to_email,
          subject: email.subject || "(无主题)",
          status: mapEmailStatus(email.status),
          body_html: email.body_html || null,
          body_text: email.body_text || null,
          cc_emails: email.cc_emails || [],
          bcc_emails: email.bcc_emails || [],
          sent_at: email.sent_at || null,
          delivered_at: email.delivered_at || null,
          read_at: email.read_at || null,
          failed_at: email.failed_at || null,
          failure_reason: email.failure_reason || null,
          message_id: email.message_id || null,
          thread_id: email.thread_id || null,
          reply_to_message_id: email.reply_to_message_id || null,
          in_reply_to: email.reply_to_message_id || null,
          attachments: email.attachments || [],
          has_attachments: (email.attachments?.length || 0) > 0,
          imap_uid: email.metadata?.imap_uid ? parseInt(email.metadata.imap_uid) : null,
          metadata: {
            ...email.metadata || {},
            category: category,
            source: "dify_imap"
          },
          cc: email.cc_emails?.join(", ") || null
        };
        // 插入数据库
        const { data, error } = await supabase.from("emails").insert(emailRecord).select("id").single();
        if (error) {
          throw new Error(`Database insert error: ${error.message}`);
        }
        successCount++;
        // 触发业务动作
        await triggerBusinessAction(supabase, email, category, data.id);
        results.push({
          email_id: data.id,
          from: email.from_email,
          subject: email.subject,
          category,
          is_duplicate: false
        });
        console.log(`✅ [email-fetch] Saved email: id=${data.id}, category=${category}`);
      } catch (e) {
        const errorMsg = e instanceof Error ? e.message : String(e);
        const errorStack = e instanceof Error ? e.stack : undefined;
        errors.push({
          subject: email.subject,
          from: email.from_email,
          error: errorMsg,
          stack: errorStack
        });
        console.error(`❌ [email-fetch] Failed to process email: ${email.subject}`, e);
      }
    }
    // 3. 更新同步状态
    const lastError = errors.length > 0 ? errors.map((e)=>e.error).join("; ") : null;
    await updateSyncState(supabase, successCount, duplicateCount, lastError);
    // 4. 返回结果（包含所有错误）
    const response = {
      success: errors.length === 0,
      trace_id: traceId,
      total_fetched: emails.length,
      new_emails: successCount,
      duplicates: duplicateCount,
      skipped: skippedCount,
      emails: results,
      errors: errors,
      skipped_emails: skipped
    };
    console.log("✅ [email-fetch] Completed:", {
      ...response,
      errors_count: errors.length,
      skipped_count: skippedCount
    });
    return new Response(JSON.stringify(response), {
      status: errors.length > 0 ? 207 : 200,
      headers: {
        ...corsHeaders,
        "Content-Type": "application/json"
      }
    });
  } catch (error) {
    console.error("❌ [email-fetch] 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"
      }
    });
  }
});
