import { serve } from "https://deno.land/std@0.168.0/http/server.ts";
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 OperationRequest {
  operation: string;
  params: Record<string, any>;
}

/**
 * 营销经理(小营)专属操作函数
 * 负责活动策划、促销推广、优惠券管理、用户增长
 */
serve(async (req) => {
  if (req.method === 'OPTIONS') {
    return new Response(null, { headers: corsHeaders });
  }

  try {
    const authHeader = req.headers.get('Authorization');
    if (!authHeader) {
      throw new Error('未授权访问');
    }

    const supabase = createClient(
      Deno.env.get('SUPABASE_URL') ?? '',
      Deno.env.get('SUPABASE_ANON_KEY') ?? '',
      {
        auth: { persistSession: false, autoRefreshToken: false },
        global: { headers: { Authorization: authHeader } },
      }
    );

    const { data: { user } } = await supabase.auth.getUser();
    if (!user) throw new Error('用户未认证');

    const { data: profile } = await supabase
      .from('profiles')
      .select('role')
      .eq('user_id', user.id)
      .single();

    if (!profile || profile.role !== 'admin') {
      throw new Error('需要管理员权限');
    }

    const { operation, params } = await req.json() as OperationRequest;
    console.log('[Marketing-Ops] 执行操作:', operation, params);

    let result;

    switch (operation) {
      // ==================== 优惠券管理 ====================
      case 'coupon.query': {
        let query = supabase.from('coupons').select('*');
        if (params.status) query = query.eq('status', params.status);
        if (params.type) query = query.eq('type', params.type);
        if (params.scope) query = query.eq('scope', params.scope);
        if (params.keyword) {
          query = query.or(`name.ilike.%${params.keyword}%,code.ilike.%${params.keyword}%`);
        }
        
        const { data, error } = await query.order('created_at', { ascending: false });
        if (error) throw error;
        result = { data, count: data?.length || 0 };
        break;
      }

      case 'coupon.create': {
        const couponCode = params.code || `COUPON${Date.now().toString(36).toUpperCase()}`;
        
        const couponData = {
          name: params.name,
          code: couponCode,
          type: params.type || 'percentage',
          discount_value: params.discount_value,
          min_purchase_amount: params.min_purchase_amount || 0,
          max_discount_amount: params.max_discount_amount,
          start_date: params.start_date,
          end_date: params.end_date,
          total_quantity: params.total_quantity || 100,
          per_user_limit: params.per_user_limit || 1,
          scope: params.scope || 'all',
          scope_ids: params.scope_ids,
          description: params.description,
          status: params.status || 'active',
        };
        
        const { data, error } = await supabase.from('coupons').insert(couponData).select().single();
        if (error) throw error;
        result = { data, message: `优惠券 "${params.name}" 创建成功，优惠券码: ${couponCode}` };
        break;
      }

      case 'coupon.update': {
        const { id, ...updates } = params;
        updates.updated_at = new Date().toISOString();
        const { data, error } = await supabase.from('coupons').update(updates).eq('id', id).select().single();
        if (error) throw error;
        result = { data, message: '优惠券更新成功' };
        break;
      }

      case 'coupon.delete': {
        const { error } = await supabase.from('coupons').delete().eq('id', params.id);
        if (error) throw error;
        result = { message: '优惠券删除成功' };
        break;
      }

      case 'coupon.toggleStatus': {
        const { data, error } = await supabase.from('coupons')
          .update({ status: params.status })
          .eq('id', params.id)
          .select().single();
        if (error) throw error;
        result = { data, message: `优惠券状态已更新为 ${params.status}` };
        break;
      }

      // ==================== 营销活动管理 ====================
      case 'campaign.query': {
        let query = supabase.from('marketing_campaigns').select('*, coupons(*)');
        if (params.status) query = query.eq('status', params.status);
        if (params.type) query = query.eq('type', params.type);
        if (params.created_by) query = query.eq('created_by', params.created_by);
        if (params.keyword) {
          query = query.or(`name.ilike.%${params.keyword}%,description.ilike.%${params.keyword}%`);
        }
        if (params.startDate) query = query.gte('start_date', params.startDate);
        if (params.endDate) query = query.lte('end_date', params.endDate);
        
        const { data, error } = await query.order('created_at', { ascending: false });
        if (error) throw error;
        result = { data, count: data?.length || 0 };
        break;
      }

      case 'campaign.create': {
        const campaignData = {
          name: params.name,
          description: params.description,
          type: params.type || 'promotion',
          start_date: params.start_date,
          end_date: params.end_date,
          status: params.status || 'draft',
          config: params.config || {},
          ai_strategy: params.ai_strategy,
          related_coupon_id: params.related_coupon_id,
          created_by: params.created_by || 'AI',
          created_by_user_id: user.id
        };
        
        const { data, error } = await supabase.from('marketing_campaigns').insert(campaignData).select().single();
        if (error) throw error;
        result = { data, message: `营销活动 "${params.name}" 创建成功` };
        break;
      }

      case 'campaign.update': {
        const { id, ...updates } = params;
        updates.updated_at = new Date().toISOString();
        const { data, error } = await supabase.from('marketing_campaigns').update(updates).eq('id', id).select().single();
        if (error) throw error;
        result = { data, message: '营销活动更新成功' };
        break;
      }

      case 'campaign.delete': {
        const { error } = await supabase.from('marketing_campaigns').delete().eq('id', params.id);
        if (error) throw error;
        result = { message: '营销活动删除成功' };
        break;
      }

      case 'campaign.approve': {
        const { data, error } = await supabase.from('marketing_campaigns')
          .update({
            status: 'active',
            review_notes: params.review_notes,
            reviewed_by: user.id,
            reviewed_at: new Date().toISOString()
          })
          .eq('id', params.id)
          .select().single();
        if (error) throw error;
        result = { data, message: '营销活动已审核通过' };
        break;
      }

      case 'campaign.reject': {
        const { data, error } = await supabase.from('marketing_campaigns')
          .update({
            status: 'rejected',
            review_notes: params.review_notes,
            reviewed_by: user.id,
            reviewed_at: new Date().toISOString()
          })
          .eq('id', params.id)
          .select().single();
        if (error) throw error;
        result = { data, message: '营销活动已被拒绝' };
        break;
      }

      case 'campaign.pause': {
        const { data, error } = await supabase.from('marketing_campaigns')
          .update({ status: 'paused' })
          .eq('id', params.id)
          .select().single();
        if (error) throw error;
        result = { data, message: '营销活动已暂停' };
        break;
      }

      case 'campaign.resume': {
        const { data, error } = await supabase.from('marketing_campaigns')
          .update({ status: 'active' })
          .eq('id', params.id)
          .select().single();
        if (error) throw error;
        result = { data, message: '营销活动已恢复' };
        break;
      }

      // ==================== 秒杀/限时折扣 ====================
      case 'flashSale.query': {
        let query = supabase.from('flash_sales').select('*, products(id, name, image_url)');
        if (params.status) query = query.eq('status', params.status);
        if (params.type) query = query.eq('type', params.type);
        if (params.product_id) query = query.eq('product_id', params.product_id);
        if (params.startDate) query = query.gte('start_time', params.startDate);
        if (params.endDate) query = query.lte('end_time', params.endDate);
        
        const { data, error } = await query.order('created_at', { ascending: false });
        if (error) throw error;
        result = { data, count: data?.length || 0 };
        break;
      }

      case 'flashSale.create': {
        const flashData = {
          name: params.name,
          product_id: params.product_id,
          flash_price: params.flash_price,
          original_price: params.original_price,
          stock_limit: params.stock_limit,
          start_time: params.start_time,
          end_time: params.end_time,
          type: params.type || 'flash_sale',
          per_user_limit: params.per_user_limit,
          description: params.description,
          ai_strategy: params.ai_strategy,
          status: params.status || 'draft',
          created_by: user.id
        };
        
        const { data, error } = await supabase.from('flash_sales').insert(flashData).select().single();
        if (error) throw error;
        result = { data, message: `秒杀活动 "${params.name}" 创建成功` };
        break;
      }

      case 'flashSale.update': {
        const { id, ...updates } = params;
        updates.updated_at = new Date().toISOString();
        const { data, error } = await supabase.from('flash_sales').update(updates).eq('id', id).select().single();
        if (error) throw error;
        result = { data, message: '秒杀活动更新成功' };
        break;
      }

      case 'flashSale.delete': {
        const { error } = await supabase.from('flash_sales').delete().eq('id', params.id);
        if (error) throw error;
        result = { message: '秒杀活动删除成功' };
        break;
      }

      case 'flashSale.start': {
        const { data, error } = await supabase.from('flash_sales')
          .update({ status: 'active', start_time: new Date().toISOString() })
          .eq('id', params.id)
          .select().single();
        if (error) throw error;
        result = { data, message: '秒杀活动已开始' };
        break;
      }

      case 'flashSale.stop': {
        const { data, error } = await supabase.from('flash_sales')
          .update({ status: 'ended', end_time: new Date().toISOString() })
          .eq('id', params.id)
          .select().single();
        if (error) throw error;
        result = { data, message: '秒杀活动已停止' };
        break;
      }

      // ==================== 支付有礼 ====================
      case 'paymentGift.query': {
        let query = supabase.from('payment_gifts').select('*');
        if (params.status) query = query.eq('status', params.status);
        if (params.gift_type) query = query.eq('gift_type', params.gift_type);
        if (params.min_amount) query = query.gte('min_payment_amount', params.min_amount);
        
        const { data, error } = await query.order('created_at', { ascending: false });
        if (error) throw error;
        result = { data, count: data?.length || 0 };
        break;
      }

      case 'paymentGift.create': {
        const giftData = {
          name: params.name,
          min_payment_amount: params.min_payment_amount,
          gift_type: params.gift_type,
          gift_value: params.gift_value,
          probability: params.probability || 100,
          start_date: params.start_date,
          end_date: params.end_date,
          total_quantity: params.total_quantity,
          description: params.description,
          ai_strategy: params.ai_strategy,
          status: params.status || 'draft',
          created_by: user.id
        };
        
        const { data, error } = await supabase.from('payment_gifts').insert(giftData).select().single();
        if (error) throw error;
        result = { data, message: `支付有礼活动 "${params.name}" 创建成功` };
        break;
      }

      case 'paymentGift.update': {
        const { id, ...updates } = params;
        updates.updated_at = new Date().toISOString();
        const { data, error } = await supabase.from('payment_gifts').update(updates).eq('id', id).select().single();
        if (error) throw error;
        result = { data, message: '支付有礼活动更新成功' };
        break;
      }

      case 'paymentGift.delete': {
        const { error } = await supabase.from('payment_gifts').delete().eq('id', params.id);
        if (error) throw error;
        result = { message: '支付有礼活动删除成功' };
        break;
      }

      // ==================== 团购活动 ====================
      case 'groupBuy.query': {
        let query = supabase.from('group_buy_activities').select('*, products(id, name, image_url)');
        if (params.status) query = query.eq('status', params.status);
        if (params.product_id) query = query.eq('product_id', params.product_id);
        if (params.startDate) query = query.gte('start_date', params.startDate);
        if (params.endDate) query = query.lte('end_date', params.endDate);
        
        const { data, error } = await query.order('created_at', { ascending: false });
        if (error) throw error;
        result = { data, count: data?.length || 0 };
        break;
      }

      case 'groupBuy.create': {
        const groupData = {
          name: params.name,
          product_id: params.product_id,
          group_price: params.group_price,
          original_price: params.original_price,
          min_group_size: params.min_group_size,
          max_group_size: params.max_group_size || params.min_group_size * 2,
          duration_hours: params.duration_hours,
          start_date: params.start_date,
          end_date: params.end_date,
          stock_limit: params.stock_limit,
          description: params.description,
          ai_strategy: params.ai_strategy,
          status: params.status || 'draft',
          created_by: user.id
        };
        
        const { data, error } = await supabase.from('group_buy_activities').insert(groupData).select().single();
        if (error) throw error;
        result = { data, message: `团购活动 "${params.name}" 创建成功` };
        break;
      }

      case 'groupBuy.update': {
        const { id, ...updates } = params;
        updates.updated_at = new Date().toISOString();
        const { data, error } = await supabase.from('group_buy_activities').update(updates).eq('id', id).select().single();
        if (error) throw error;
        result = { data, message: '团购活动更新成功' };
        break;
      }

      case 'groupBuy.delete': {
        const { error } = await supabase.from('group_buy_activities').delete().eq('id', params.id);
        if (error) throw error;
        result = { message: '团购活动删除成功' };
        break;
      }

      // ==================== 会员储值 ====================
      case 'recharge.queryPlans': {
        let query = supabase.from('recharge_plans').select('*');
        if (params.is_active !== undefined) query = query.eq('is_active', params.is_active);
        
        const { data, error } = await query.order('display_order', { ascending: true });
        if (error) throw error;
        result = { data, count: data?.length || 0 };
        break;
      }

      case 'recharge.createPlan': {
        const planData = {
          name: params.name,
          recharge_amount: params.recharge_amount,
          bonus_amount: params.bonus_amount,
          description: params.description,
          display_order: params.display_order,
          is_active: params.is_active !== false
        };
        
        const { data, error } = await supabase.from('recharge_plans').insert(planData).select().single();
        if (error) throw error;
        result = { data, message: `储值方案 "${params.name}" 创建成功` };
        break;
      }

      case 'recharge.updatePlan': {
        const { id, ...updates } = params;
        updates.updated_at = new Date().toISOString();
        const { data, error } = await supabase.from('recharge_plans').update(updates).eq('id', id).select().single();
        if (error) throw error;
        result = { data, message: '储值方案更新成功' };
        break;
      }

      case 'recharge.deletePlan': {
        const { error } = await supabase.from('recharge_plans').delete().eq('id', params.id);
        if (error) throw error;
        result = { message: '储值方案删除成功' };
        break;
      }

      // ==================== 营销分析 ====================
      case 'analytics.campaigns': {
        const { data: campaigns, error } = await supabase.from('marketing_campaigns')
          .select('id, name, type, status, created_by, start_date, end_date, created_at')
          .order('created_at', { ascending: false })
          .limit(params.limit || 20);
        
        if (error) throw error;
        
        const statusCounts = campaigns?.reduce((acc, c) => {
          acc[c.status] = (acc[c.status] || 0) + 1;
          return acc;
        }, {} as Record<string, number>) || {};
        
        const typeCounts = campaigns?.reduce((acc, c) => {
          acc[c.type] = (acc[c.type] || 0) + 1;
          return acc;
        }, {} as Record<string, number>) || {};
        
        result = {
          totalCampaigns: campaigns?.length || 0,
          statusDistribution: statusCounts,
          typeDistribution: typeCounts,
          data: campaigns
        };
        break;
      }

      case 'analytics.marketing': {
        const dateFilter = {
          start: params.startDate || new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString(),
          end: params.endDate || new Date().toISOString()
        };

        const [flashSales, paymentGifts, groupBuys, coupons] = await Promise.all([
          supabase.from('flash_sales').select('id, status, sold_count, stock_limit').gte('created_at', dateFilter.start).lte('created_at', dateFilter.end),
          supabase.from('payment_gifts').select('id, status, used_quantity, total_quantity').gte('created_at', dateFilter.start).lte('created_at', dateFilter.end),
          supabase.from('group_buy_activities').select('id, status, sold_count').gte('created_at', dateFilter.start).lte('created_at', dateFilter.end),
          supabase.from('coupons').select('id, status, used_quantity, total_quantity').gte('created_at', dateFilter.start).lte('created_at', dateFilter.end)
        ]);

        result = {
          flashSales: {
            total: flashSales.data?.length || 0,
            active: flashSales.data?.filter(f => f.status === 'active').length || 0,
            totalSold: flashSales.data?.reduce((sum, f) => sum + (f.sold_count || 0), 0) || 0
          },
          paymentGifts: {
            total: paymentGifts.data?.length || 0,
            active: paymentGifts.data?.filter(p => p.status === 'active').length || 0,
            totalUsed: paymentGifts.data?.reduce((sum, p) => sum + (p.used_quantity || 0), 0) || 0
          },
          groupBuys: {
            total: groupBuys.data?.length || 0,
            active: groupBuys.data?.filter(g => g.status === 'active').length || 0,
            totalSold: groupBuys.data?.reduce((sum, g) => sum + (g.sold_count || 0), 0) || 0
          },
          coupons: {
            total: coupons.data?.length || 0,
            active: coupons.data?.filter(c => c.status === 'active').length || 0,
            totalUsed: coupons.data?.reduce((sum, c) => sum + (c.used_quantity || 0), 0) || 0
          },
          dateRange: dateFilter
        };
        break;
      }

      // ==================== 跨店联合促销 ====================
      case 'crossStore.query': {
        let query = supabase.from('cross_store_promotions').select('*');
        if (params.status) query = query.eq('status', params.status);
        if (params.type) query = query.eq('type', params.type);
        if (params.keyword) {
          query = query.or(`name.ilike.%${params.keyword}%,description.ilike.%${params.keyword}%`);
        }
        if (params.startDate) query = query.gte('start_date', params.startDate);
        if (params.endDate) query = query.lte('end_date', params.endDate);
        
        const { data, error } = await query.order('created_at', { ascending: false });
        if (error) throw error;
        result = { data, count: data?.length || 0 };
        break;
      }

      case 'crossStore.create': {
        const promotionData = {
          name: params.name,
          description: params.description,
          type: params.type || 'joint_discount',
          store_ids: params.store_ids || [],
          config: params.config || {},
          start_date: params.start_date,
          end_date: params.end_date,
          total_budget: params.total_budget || 0,
          max_participants: params.max_participants,
          ai_strategy: params.ai_strategy,
          status: params.status || 'draft',
          created_by: params.created_by || 'manual',
          created_by_user_id: user.id
        };
        
        const { data, error } = await supabase.from('cross_store_promotions').insert(promotionData).select().single();
        if (error) throw error;
        result = { data, message: `跨店促销活动 "${params.name}" 创建成功` };
        break;
      }

      case 'crossStore.update': {
        const { id, ...updates } = params;
        updates.updated_at = new Date().toISOString();
        const { data, error } = await supabase.from('cross_store_promotions').update(updates).eq('id', id).select().single();
        if (error) throw error;
        result = { data, message: '跨店促销活动更新成功' };
        break;
      }

      case 'crossStore.delete': {
        const { error } = await supabase.from('cross_store_promotions').delete().eq('id', params.id);
        if (error) throw error;
        result = { message: '跨店促销活动删除成功' };
        break;
      }

      case 'crossStore.approve': {
        const { data, error } = await supabase.from('cross_store_promotions')
          .update({
            status: 'active',
            review_notes: params.review_notes,
            reviewed_by: user.id,
            reviewed_at: new Date().toISOString()
          })
          .eq('id', params.id)
          .select().single();
        if (error) throw error;
        result = { data, message: '跨店促销活动已审核通过' };
        break;
      }

      case 'crossStore.reject': {
        const { data, error } = await supabase.from('cross_store_promotions')
          .update({
            status: 'rejected',
            review_notes: params.review_notes,
            reviewed_by: user.id,
            reviewed_at: new Date().toISOString()
          })
          .eq('id', params.id)
          .select().single();
        if (error) throw error;
        result = { data, message: '跨店促销活动已被拒绝' };
        break;
      }

      case 'crossStore.pause': {
        const { data, error } = await supabase.from('cross_store_promotions')
          .update({ status: 'paused' })
          .eq('id', params.id)
          .select().single();
        if (error) throw error;
        result = { data, message: '跨店促销活动已暂停' };
        break;
      }

      case 'crossStore.resume': {
        const { data, error } = await supabase.from('cross_store_promotions')
          .update({ status: 'active' })
          .eq('id', params.id)
          .select().single();
        if (error) throw error;
        result = { data, message: '跨店促销活动已恢复' };
        break;
      }

      // 跨店促销参与店铺管理
      case 'crossStore.addStore': {
        const storeData = {
          promotion_id: params.promotion_id,
          store_name: params.store_name,
          store_type: params.store_type,
          contribution_ratio: params.contribution_ratio || 0,
        };
        
        const { data, error } = await supabase.from('cross_store_promotion_stores').insert(storeData).select().single();
        if (error) throw error;
        result = { data, message: `店铺 "${params.store_name}" 已加入跨店促销` };
        break;
      }

      case 'crossStore.removeStore': {
        const { error } = await supabase.from('cross_store_promotion_stores').delete().eq('id', params.id);
        if (error) throw error;
        result = { message: '店铺已从跨店促销中移除' };
        break;
      }

      case 'crossStore.queryStores': {
        const { data, error } = await supabase.from('cross_store_promotion_stores')
          .select('*')
          .eq('promotion_id', params.promotion_id)
          .order('joined_at', { ascending: false });
        if (error) throw error;
        result = { data, count: data?.length || 0 };
        break;
      }

      default:
        throw new Error(`[Marketing-Ops] 不支持的操作类型: ${operation}`);
    }

    return new Response(
      JSON.stringify({ success: true, ...result }),
      { headers: { ...corsHeaders, 'Content-Type': 'application/json' }, status: 200 }
    );

  } catch (error) {
    console.error('[Marketing-Ops] 操作执行错误:', error);
    return new Response(
      JSON.stringify({
        success: false,
        error: (error instanceof Error ? error.message : '未知错误')
      }),
      { headers: { ...corsHeaders, 'Content-Type': 'application/json' }, status: 400 }
    );
  }
});
