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('[Service-Ops] 执行操作:', operation, params);

    let result;

    switch (operation) {
      // ==================== 订单管理 ====================
      case 'order.query': {
        let query = supabase.from('orders').select('*, order_items(*, products(*))');
        if (params.status) query = query.eq('status', params.status);
        if (params.userId) query = query.eq('user_id', params.userId);
        if (params.orderNumber) query = query.eq('order_number', params.orderNumber);
        if (params.startDate) query = query.gte('created_at', params.startDate);
        if (params.endDate) query = query.lte('created_at', params.endDate);
        if (params.minAmount) query = query.gte('total_amount', params.minAmount);
        if (params.maxAmount) query = query.lte('total_amount', params.maxAmount);
        
        const { data, error } = await query.order('created_at', { ascending: false });
        if (error) throw error;
        result = { data, count: data?.length || 0 };
        break;
      }

      case 'order.update':
      case 'order.updateStatus': {
        const { id, ...updates } = params;
        updates.updated_at = new Date().toISOString();
        const { data, error } = await supabase.from('orders').update(updates).eq('id', id).select().single();
        if (error) throw error;
        result = { data, message: '订单更新成功' };
        break;
      }

      case 'order.addTracking': {
        const { data, error } = await supabase.from('orders')
          .update({ 
            tracking_number: params.tracking_number,
            status: 'shipped',
            shipped_at: new Date().toISOString(),
            updated_at: new Date().toISOString()
          })
          .eq('id', params.id)
          .select().single();
        if (error) throw error;
        result = { data, message: '物流单号添加成功，订单已发货' };
        break;
      }

      case 'order.cancel': {
        const { data, error } = await supabase.from('orders')
          .update({ 
            status: 'cancelled',
            notes: params.reason || '订单已取消',
            updated_at: new Date().toISOString()
          })
          .eq('id', params.id)
          .select().single();
        if (error) throw error;
        result = { data, message: '订单已取消' };
        break;
      }

      case 'order.refund': {
        const { data, error } = await supabase.from('orders')
          .update({ 
            status: 'refunded',
            notes: `退款金额: ¥${params.amount}, 原因: ${params.reason || '无'}`,
            updated_at: new Date().toISOString()
          })
          .eq('id', params.id)
          .select().single();
        if (error) throw error;
        result = { data, message: `退款处理成功，退款金额: ¥${params.amount}` };
        break;
      }

      case 'order.addNote': {
        const { data: current } = await supabase.from('orders')
          .select('notes')
          .eq('id', params.id)
          .single();
        
        const newNotes = current?.notes 
          ? `${current.notes}\n[${new Date().toLocaleString()}] ${params.note}`
          : `[${new Date().toLocaleString()}] ${params.note}`;

        const { data, error } = await supabase.from('orders')
          .update({ notes: newNotes, updated_at: new Date().toISOString() })
          .eq('id', params.id)
          .select().single();
        if (error) throw error;
        result = { data, message: '备注添加成功' };
        break;
      }

      // ==================== 售后管理 ====================
      case 'afterSales.query': {
        let query = supabase.from('after_sales_requests').select('*, orders(*), products(*)');
        if (params.status) query = query.eq('status', params.status);
        if (params.type) query = query.eq('type', params.type);
        if (params.userId) query = query.eq('user_id', params.userId);
        if (params.orderId) query = query.eq('order_id', params.orderId);
        if (params.startDate) query = query.gte('created_at', params.startDate);
        if (params.endDate) query = query.lte('created_at', params.endDate);
        
        const { data, error } = await query.order('created_at', { ascending: false });
        if (error) throw error;
        result = { data, count: data?.length || 0 };
        break;
      }

      case 'afterSales.update': {
        const { id, ...updates } = params;
        updates.updated_at = new Date().toISOString();
        const { data, error } = await supabase.from('after_sales_requests')
          .update(updates)
          .eq('id', id)
          .select().single();
        if (error) throw error;
        result = { data, message: '售后信息更新成功' };
        break;
      }

      case 'afterSales.approve': {
        const { data, error } = await supabase.from('after_sales_requests')
          .update({
            status: 'approved',
            refund_amount: params.refund_amount,
            admin_notes: params.admin_notes,
            processed_at: new Date().toISOString(),
            processed_by: user.id,
            updated_at: new Date().toISOString()
          })
          .eq('id', params.id)
          .select().single();
        if (error) throw error;
        result = { data, message: '售后请求已批准' };
        break;
      }

      case 'afterSales.reject': {
        const { data, error } = await supabase.from('after_sales_requests')
          .update({
            status: 'rejected',
            admin_notes: params.reason,
            processed_at: new Date().toISOString(),
            processed_by: user.id,
            updated_at: new Date().toISOString()
          })
          .eq('id', params.id)
          .select().single();
        if (error) throw error;
        result = { data, message: '售后请求已拒绝' };
        break;
      }

      case 'afterSales.addNotes': {
        const { data: current } = await supabase.from('after_sales_requests')
          .select('admin_notes')
          .eq('id', params.id)
          .single();
        
        const newNotes = current?.admin_notes 
          ? `${current.admin_notes}\n[${new Date().toLocaleString()}] ${params.notes}`
          : `[${new Date().toLocaleString()}] ${params.notes}`;

        const { data, error } = await supabase.from('after_sales_requests')
          .update({ admin_notes: newNotes, updated_at: new Date().toISOString() })
          .eq('id', params.id)
          .select().single();
        if (error) throw error;
        result = { data, message: '备注添加成功' };
        break;
      }

      case 'afterSales.setTracking': {
        const { data, error } = await supabase.from('after_sales_requests')
          .update({ 
            tracking_number: params.tracking_number, 
            status: 'processing',
            updated_at: new Date().toISOString() 
          })
          .eq('id', params.id)
          .select().single();
        if (error) throw error;
        result = { data, message: '退货物流单号已添加' };
        break;
      }

      case 'afterSales.complete': {
        const { data, error } = await supabase.from('after_sales_requests')
          .update({ 
            status: 'completed',
            processed_at: new Date().toISOString(),
            processed_by: user.id,
            admin_notes: params.admin_notes,
            updated_at: new Date().toISOString()
          })
          .eq('id', params.id)
          .select().single();
        if (error) throw error;
        result = { data, message: '售后已完成处理' };
        break;
      }

      // ==================== 用户管理 ====================
      case 'user.query': {
        let query = supabase.from('profiles').select('*');
        if (params.keyword) {
          query = query.or(`display_name.ilike.%${params.keyword}%,phone.ilike.%${params.keyword}%`);
        }
        if (params.role) query = query.eq('role', params.role);
        if (params.emailVerified !== undefined) query = query.eq('email_verified', params.emailVerified);
        
        const { data, error } = await query.order('created_at', { ascending: false });
        if (error) throw error;
        result = { data, count: data?.length || 0 };
        break;
      }

      case 'user.update': {
        const { id, ...updates } = params;
        updates.updated_at = new Date().toISOString();
        const { data, error } = await supabase.from('profiles').update(updates).eq('id', id).select().single();
        if (error) throw error;
        result = { data, message: '用户信息更新成功' };
        break;
      }

      case 'user.getOrders': {
        const { data, error } = await supabase.from('orders')
          .select('*, order_items(*, products(*))')
          .eq('user_id', params.userId)
          .order('created_at', { ascending: false });
        if (error) throw error;
        result = { data, count: data?.length || 0 };
        break;
      }

      case 'user.getAfterSales': {
        const { data, error } = await supabase.from('after_sales_requests')
          .select('*, orders(*), products(*)')
          .eq('user_id', params.userId)
          .order('created_at', { ascending: false });
        if (error) throw error;
        result = { data, count: data?.length || 0 };
        break;
      }

      // ==================== 余额管理 ====================
      case 'balance.query': {
        let query = supabase.from('user_balances').select('*, profiles(display_name, avatar_url, phone)');
        if (params.user_id) query = query.eq('user_id', params.user_id);
        if (params.min_balance) query = query.gte('balance', params.min_balance);
        if (params.max_balance) query = query.lte('balance', params.max_balance);
        
        const { data, error } = await query.order('balance', { ascending: false });
        if (error) throw error;
        result = { data, count: data?.length || 0 };
        break;
      }

      case 'balance.queryTransactions': {
        let query = supabase.from('balance_transactions').select('*, profiles(display_name)');
        if (params.user_id) query = query.eq('user_id', params.user_id);
        if (params.type) query = query.eq('type', params.type);
        if (params.startDate) query = query.gte('created_at', params.startDate);
        if (params.endDate) query = query.lte('created_at', params.endDate);
        
        const { data, error } = await query.order('created_at', { ascending: false }).limit(params.limit || 100);
        if (error) throw error;
        result = { data, count: data?.length || 0 };
        break;
      }

      case 'balance.adjust': {
        // 先获取当前余额
        const { data: currentBalance, error: fetchError } = await supabase
          .from('user_balances')
          .select('*')
          .eq('user_id', params.user_id)
          .single();
        
        if (fetchError && fetchError.code !== 'PGRST116') throw fetchError;
        
        const oldBalance = currentBalance?.balance || 0;
        const newBalance = oldBalance + params.amount;
        
        if (newBalance < 0) {
          throw new Error('余额不足');
        }
        
        // 更新或创建余额记录
        if (currentBalance) {
          const { error: updateError } = await supabase
            .from('user_balances')
            .update({ balance: newBalance, updated_at: new Date().toISOString() })
            .eq('user_id', params.user_id);
          if (updateError) throw updateError;
        } else {
          const { error: insertError } = await supabase
            .from('user_balances')
            .insert({ user_id: params.user_id, balance: newBalance });
          if (insertError) throw insertError;
        }
        
        // 记录交易
        const { error: txError } = await supabase
          .from('balance_transactions')
          .insert({
            user_id: params.user_id,
            type: 'adjust',
            amount: params.amount,
            balance_before: oldBalance,
            balance_after: newBalance,
            description: params.description || '客服调整'
          });
        if (txError) throw txError;
        
        result = { 
          data: { user_id: params.user_id, old_balance: oldBalance, new_balance: newBalance },
          message: `余额调整成功，当前余额: ¥${newBalance}` 
        };
        break;
      }

      // ==================== 服务分析 ====================
      case 'analytics.orders': {
        let query = supabase.from('orders').select('status, created_at, total_amount');
        if (params.startDate) query = query.gte('created_at', params.startDate);
        if (params.endDate) query = query.lte('created_at', params.endDate);
        
        const { data, error } = await query;
        if (error) throw error;
        
        const statusCounts = data?.reduce((acc, order) => {
          acc[order.status] = (acc[order.status] || 0) + 1;
          return acc;
        }, {} as Record<string, number>) || {};
        
        const totalAmount = data?.reduce((sum, order) => sum + Number(order.total_amount || 0), 0) || 0;
        
        result = {
          totalOrders: data?.length || 0,
          totalAmount,
          statusDistribution: statusCounts,
          averageOrderValue: data?.length ? totalAmount / data.length : 0
        };
        break;
      }

      case 'analytics.afterSales': {
        let query = supabase.from('after_sales_requests').select('status, type, created_at, refund_amount');
        if (params.startDate) query = query.gte('created_at', params.startDate);
        if (params.endDate) query = query.lte('created_at', params.endDate);
        
        const { data, error } = await query;
        if (error) throw error;
        
        const statusCounts = data?.reduce((acc, item) => {
          acc[item.status] = (acc[item.status] || 0) + 1;
          return acc;
        }, {} as Record<string, number>) || {};
        
        const typeCounts = data?.reduce((acc, item) => {
          acc[item.type] = (acc[item.type] || 0) + 1;
          return acc;
        }, {} as Record<string, number>) || {};
        
        const totalRefund = data?.reduce((sum, item) => sum + Number(item.refund_amount || 0), 0) || 0;
        
        result = {
          totalRequests: data?.length || 0,
          totalRefund,
          statusDistribution: statusCounts,
          typeDistribution: typeCounts,
          pendingCount: statusCounts['pending'] || 0,
          approvedCount: statusCounts['approved'] || 0,
          rejectedCount: statusCounts['rejected'] || 0
        };
        break;
      }

      case 'analytics.satisfaction': {
        // 计算客户满意度指标
        const [orders, afterSales] = await Promise.all([
          supabase.from('orders').select('status').gte('created_at', params.startDate || new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString()),
          supabase.from('after_sales_requests').select('status').gte('created_at', params.startDate || new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString())
        ]);
        
        const completedOrders = orders.data?.filter(o => o.status === 'completed').length || 0;
        const totalOrders = orders.data?.length || 0;
        const approvedAfterSales = afterSales.data?.filter(a => a.status === 'approved' || a.status === 'completed').length || 0;
        const totalAfterSales = afterSales.data?.length || 0;
        
        result = {
          orderCompletionRate: totalOrders > 0 ? (completedOrders / totalOrders * 100).toFixed(1) + '%' : '0%',
          afterSalesResolutionRate: totalAfterSales > 0 ? (approvedAfterSales / totalAfterSales * 100).toFixed(1) + '%' : '0%',
          totalOrders,
          completedOrders,
          totalAfterSales,
          resolvedAfterSales: approvedAfterSales
        };
        break;
      }

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

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

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