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 AlertData {
  alert_type: string;
  category: "inventory" | "order" | "marketing" | "finance" | "service" | "system";
  severity: "info" | "warning" | "critical";
  title: string;
  description: string;
  data?: Record<string, unknown>;
  target_agent: string;
  expires_at?: string;
}

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

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

  console.log("[InsightsMonitor] Starting business monitoring...");

  const alerts: AlertData[] = [];
  const now = new Date();
  const oneDayAgo = new Date(now.getTime() - 24 * 60 * 60 * 1000);
  const sevenDaysAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);

  try {
    // ========== 1. 库存监控 ==========
    const { data: lowStockProducts } = await supabase
      .from("products")
      .select("id, name, stock_quantity, monthly_sales")
      .eq("is_active", true)
      .lt("stock_quantity", 10)
      .order("stock_quantity", { ascending: true })
      .limit(10);

    if (lowStockProducts && lowStockProducts.length > 0) {
      const criticalStock = lowStockProducts.filter(p => p.stock_quantity <= 3);
      const warningStock = lowStockProducts.filter(p => p.stock_quantity > 3 && p.stock_quantity < 10);

      if (criticalStock.length > 0) {
        alerts.push({
          alert_type: "low_stock_critical",
          category: "inventory",
          severity: "critical",
          title: `${criticalStock.length} 款商品库存严重不足`,
          description: `${criticalStock.map(p => p.name).slice(0, 3).join("、")}${criticalStock.length > 3 ? " 等" : ""} 库存不足3件，需立即补货`,
          data: { products: criticalStock },
          target_agent: "product",
          expires_at: new Date(now.getTime() + 2 * 24 * 60 * 60 * 1000).toISOString(),
        });
      }

      if (warningStock.length > 0) {
        alerts.push({
          alert_type: "low_stock_warning",
          category: "inventory",
          severity: "warning",
          title: `${warningStock.length} 款商品库存偏低`,
          description: `建议尽快补货以避免断货影响销售`,
          data: { products: warningStock },
          target_agent: "product",
          expires_at: new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000).toISOString(),
        });
      }
    }

    // ========== 2. 订单异常监控 ==========
    const { data: pendingOrders } = await supabase
      .from("orders")
      .select("id, order_number, created_at, total_amount")
      .eq("status", "pending")
      .lt("created_at", oneDayAgo.toISOString());

    if (pendingOrders && pendingOrders.length > 0) {
      alerts.push({
        alert_type: "order_pending_too_long",
        category: "order",
        severity: pendingOrders.length > 5 ? "critical" : "warning",
        title: `${pendingOrders.length} 个订单超过24小时未处理`,
        description: `这些订单可能影响用户体验，请尽快处理`,
        data: { orders: pendingOrders.slice(0, 5), total_count: pendingOrders.length },
        target_agent: "manager",
        expires_at: new Date(now.getTime() + 24 * 60 * 60 * 1000).toISOString(),
      });
    }

    // ========== 3. 售后投诉监控 ==========
    const { data: pendingAfterSales } = await supabase
      .from("after_sales_requests")
      .select("id, type, reason, created_at")
      .eq("status", "pending");

    if (pendingAfterSales && pendingAfterSales.length > 0) {
      const urgentRequests = pendingAfterSales.filter(r => {
        const createdAt = new Date(r.created_at);
        return now.getTime() - createdAt.getTime() > 48 * 60 * 60 * 1000;
      });

      if (urgentRequests.length > 0) {
        alerts.push({
          alert_type: "aftersales_urgent",
          category: "service",
          severity: "critical",
          title: `${urgentRequests.length} 个售后请求超过48小时未处理`,
          description: `请立即处理以避免客户投诉升级`,
          data: { requests: urgentRequests.slice(0, 5), total_count: urgentRequests.length },
          target_agent: "service",
          expires_at: new Date(now.getTime() + 12 * 60 * 60 * 1000).toISOString(),
        });
      } else if (pendingAfterSales.length >= 5) {
        alerts.push({
          alert_type: "aftersales_backlog",
          category: "service",
          severity: "warning",
          title: `${pendingAfterSales.length} 个售后请求待处理`,
          description: `售后请求积压，建议加快处理速度`,
          data: { total_count: pendingAfterSales.length },
          target_agent: "service",
          expires_at: new Date(now.getTime() + 24 * 60 * 60 * 1000).toISOString(),
        });
      }
    }

    // ========== 4. 营销活动监控 ==========
    const threeDaysLater = new Date(now.getTime() + 3 * 24 * 60 * 60 * 1000);
    
    const { data: expiringCampaigns } = await supabase
      .from("marketing_campaigns")
      .select("id, name, end_date, status")
      .eq("status", "active")
      .lt("end_date", threeDaysLater.toISOString())
      .gt("end_date", now.toISOString());

    if (expiringCampaigns && expiringCampaigns.length > 0) {
      alerts.push({
        alert_type: "campaign_expiring",
        category: "marketing",
        severity: "info",
        title: `${expiringCampaigns.length} 个营销活动即将结束`,
        description: `${expiringCampaigns.map(c => c.name).slice(0, 2).join("、")} 将在3天内结束`,
        data: { campaigns: expiringCampaigns },
        target_agent: "marketing",
        expires_at: threeDaysLater.toISOString(),
      });
    }

    // 检查过期优惠券
    const { data: expiringCoupons } = await supabase
      .from("coupons")
      .select("id, name, code, end_date, used_quantity, total_quantity")
      .eq("status", "active")
      .lt("end_date", threeDaysLater.toISOString())
      .gt("end_date", now.toISOString());

    if (expiringCoupons && expiringCoupons.length > 0) {
      const lowUsageCoupons = expiringCoupons.filter(c => 
        c.total_quantity > 0 && (c.used_quantity || 0) / c.total_quantity < 0.3
      );

      if (lowUsageCoupons.length > 0) {
        alerts.push({
          alert_type: "coupon_low_usage",
          category: "marketing",
          severity: "warning",
          title: `${lowUsageCoupons.length} 个优惠券即将过期但使用率低`,
          description: `考虑加大推广力度或延长有效期`,
          data: { coupons: lowUsageCoupons },
          target_agent: "marketing",
          expires_at: threeDaysLater.toISOString(),
        });
      }
    }

    // ========== 5. 财务异常监控 ==========
    // 检查最近7天订单趋势
    const { data: recentOrders } = await supabase
      .from("orders")
      .select("created_at, total_amount")
      .gte("created_at", sevenDaysAgo.toISOString())
      .order("created_at", { ascending: true });

    if (recentOrders && recentOrders.length > 0) {
      const dailyRevenue: Record<string, number> = {};
      recentOrders.forEach(order => {
        const day = order.created_at.split("T")[0];
        dailyRevenue[day] = (dailyRevenue[day] || 0) + Number(order.total_amount);
      });

      const days = Object.keys(dailyRevenue).sort();
      if (days.length >= 2) {
        const lastDay = dailyRevenue[days[days.length - 1]] || 0;
        const previousDay = dailyRevenue[days[days.length - 2]] || 0;
        
        if (previousDay > 0 && lastDay < previousDay * 0.5) {
          alerts.push({
            alert_type: "revenue_drop",
            category: "finance",
            severity: "warning",
            title: "营收大幅下降",
            description: `昨日营收 ¥${lastDay.toFixed(0)} 较前日下降超过50%，请关注`,
            data: { last_day: lastDay, previous_day: previousDay, drop_rate: ((previousDay - lastDay) / previousDay * 100).toFixed(1) },
            target_agent: "finance",
            expires_at: new Date(now.getTime() + 24 * 60 * 60 * 1000).toISOString(),
          });
        }
      }
    }

    // ========== 去重：检查是否已存在相同类型的未读警报 ==========
    const alertTypesToInsert = alerts.map(a => a.alert_type);
    const { data: existingAlerts } = await supabase
      .from("business_alerts")
      .select("alert_type")
      .in("alert_type", alertTypesToInsert)
      .eq("is_read", false)
      .eq("is_dismissed", false);

    const existingTypes = new Set((existingAlerts || []).map(a => a.alert_type));
    const newAlerts = alerts.filter(a => !existingTypes.has(a.alert_type));

    // ========== 插入新警报 ==========
    if (newAlerts.length > 0) {
      const { error: insertError } = await supabase
        .from("business_alerts")
        .insert(newAlerts);

      if (insertError) {
        console.error("[InsightsMonitor] Failed to insert alerts:", insertError);
        throw insertError;
      }

      console.log(`[InsightsMonitor] Inserted ${newAlerts.length} new alerts`);
    } else {
      console.log("[InsightsMonitor] No new alerts to insert");
    }

    // ========== 清理过期警报 ==========
    const { error: deleteError } = await supabase
      .from("business_alerts")
      .delete()
      .lt("expires_at", now.toISOString());

    if (deleteError) {
      console.warn("[InsightsMonitor] Failed to clean expired alerts:", deleteError);
    }

    return new Response(
      JSON.stringify({
        success: true,
        message: `Monitoring complete. ${newAlerts.length} new alerts created.`,
        alerts_created: newAlerts.length,
        alerts_checked: alerts.length,
      }),
      { headers: { ...corsHeaders, "Content-Type": "application/json" } }
    );

  } catch (error) {
    console.error("[InsightsMonitor] Error:", error);
    return new Response(
      JSON.stringify({ success: false, error: String(error) }),
      { status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" } }
    );
  }
});
