import { serve } from "https://deno.land/std@0.168.0/http/server.ts";
import { createClient } from "https://esm.sh/@supabase/supabase-js@2";
import { z } from "../_shared/deps.ts";
import { parseJsonBody } from "../_shared/validate.ts";

const corsHeaders = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
};

// Envelope schema only — per-operation param shapes vary widely and are
// validated by Supabase RLS + downstream SQL constraints.
const EnvelopeSchema = z.object({
  operation: z.string().min(1).max(100).regex(/^[a-zA-Z][\w.-]*$/, 'operation 名称不合法'),
  params: z.record(z.any()).default({}),
});

type OperationRequest = z.infer<typeof EnvelopeSchema>;

/**
 * 店铺经理(小管)专属操作函数
 * 负责通用系统操作、跨域协调、横幅管理、全局分析
 * 其他领域操作已分离到专属函数：
 * - product-operations: 商品经理(小品)
 * - marketing-operations: 营销经理(小营)
 * - service-operations: 客服经理(小服)
 */
serve(async (req) => {
  if (req.method === 'OPTIONS') {
    return new Response(null, { headers: corsHeaders });
  }

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

    // User-context client for JWT verification (works with signing-keys)
    const userClient = createClient(
      Deno.env.get('SUPABASE_URL') ?? '',
      Deno.env.get('SUPABASE_ANON_KEY') ?? '',
      {
        auth: { persistSession: false, autoRefreshToken: false },
        global: { headers: { Authorization: authHeader } },
      }
    );

    const { data: claimsData, error: claimsErr } = await userClient.auth.getClaims(token);
    if (claimsErr || !claimsData?.claims?.sub) {
      throw new Error('用户未认证');
    }
    const userId = claimsData.claims.sub as string;

    // Service-role client for SSOT admin check via user_roles
    const supabase = createClient(
      Deno.env.get('SUPABASE_URL') ?? '',
      Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? '',
      { auth: { persistSession: false, autoRefreshToken: false } }
    );

    const { data: isAdmin, error: roleErr } = await supabase.rpc('is_admin', { _user_id: userId });
    if (roleErr || !isAdmin) {
      throw new Error('需要管理员权限');
    }

    const parsed = await parseJsonBody(req, EnvelopeSchema);
    if (!parsed.ok) {
      return new Response(
        JSON.stringify({ success: false, error: parsed.message, details: parsed.issues }),
        { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      );
    }
    const { operation, params } = parsed.data;
    console.log('[Admin-Ops] 执行操作:', operation, params);

    let result;

    switch (operation) {
      // ==================== 横幅管理 ====================
      case 'banner.query': {
        let query = supabase.from('banners').select('*');
        if (params.isActive !== undefined) query = query.eq('is_active', params.isActive);
        
        const { data, error } = await query.order('display_order', { ascending: true });
        if (error) throw error;
        result = { data, count: data?.length || 0 };
        break;
      }

      case 'banner.create': {
        const { data, error } = await supabase.from('banners').insert(params).select().single();
        if (error) throw error;
        result = { data, message: `横幅 "${params.title}" 创建成功` };
        break;
      }

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

      case 'banner.delete': {
        const { error } = await supabase.from('banners').delete().eq('id', params.id);
        if (error) throw error;
        result = { message: '横幅删除成功' };
        break;
      }

      // ==================== 全局分析(店铺经理专属) ====================
      case 'analytics.dashboard': {
        const dateFilter = {
          start: params.startDate || new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString(),
          end: params.endDate || new Date().toISOString()
        };

        // 并行获取各模块数据
        const [products, orders, users, afterSales, campaigns] = await Promise.all([
          supabase.from('products').select('id, is_active, stock_quantity').eq('is_active', true),
          supabase.from('orders').select('id, status, total_amount, created_at').gte('created_at', dateFilter.start),
          supabase.from('profiles').select('id, created_at').gte('created_at', dateFilter.start),
          supabase.from('after_sales_requests').select('id, status').gte('created_at', dateFilter.start),
          supabase.from('marketing_campaigns').select('id, status').eq('status', 'active')
        ]);

        const totalSales = orders.data?.reduce((sum, o) => sum + Number(o.total_amount || 0), 0) || 0;
        const completedOrders = orders.data?.filter(o => o.status === 'completed').length || 0;

        result = {
          products: {
            total: products.data?.length || 0,
            lowStock: products.data?.filter(p => p.stock_quantity < 10).length || 0
          },
          orders: {
            total: orders.data?.length || 0,
            completed: completedOrders,
            totalSales,
            pendingCount: orders.data?.filter(o => o.status === 'pending').length || 0
          },
          users: {
            total: users.data?.length || 0,
            newUsers: users.data?.length || 0
          },
          afterSales: {
            total: afterSales.data?.length || 0,
            pending: afterSales.data?.filter(a => a.status === 'pending').length || 0
          },
          campaigns: {
            active: campaigns.data?.length || 0
          },
          dateRange: dateFilter
        };
        break;
      }

      case 'analytics.sales': {
        let query = supabase.from('orders').select('total_amount, created_at, status');
        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 totalSales = data?.reduce((sum, order) => sum + Number(order.total_amount || 0), 0) || 0;
        const orderCount = data?.length || 0;
        
        result = {
          totalSales,
          orderCount,
          averageOrderValue: orderCount > 0 ? totalSales / orderCount : 0,
          data
        };
        break;
      }

      case 'analytics.users': {
        let query = supabase.from('profiles').select('created_at, role');
        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;
        
        result = {
          totalUsers: data?.length || 0,
          data
        };
        break;
      }

      case 'analytics.overview': {
        // 综合业务概览
        const today = new Date();
        const thirtyDaysAgo = new Date(today.getTime() - 30 * 24 * 60 * 60 * 1000);
        const sevenDaysAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);

        const [
          totalProducts,
          totalOrders,
          recentOrders,
          totalUsers,
          recentUsers,
          pendingAfterSales,
          activeCampaigns
        ] = await Promise.all([
          supabase.from('products').select('id', { count: 'exact' }).eq('is_active', true),
          supabase.from('orders').select('id', { count: 'exact' }),
          supabase.from('orders').select('total_amount').gte('created_at', sevenDaysAgo.toISOString()),
          supabase.from('profiles').select('id', { count: 'exact' }),
          supabase.from('profiles').select('id', { count: 'exact' }).gte('created_at', thirtyDaysAgo.toISOString()),
          supabase.from('after_sales_requests').select('id', { count: 'exact' }).eq('status', 'pending'),
          supabase.from('marketing_campaigns').select('id', { count: 'exact' }).eq('status', 'active')
        ]);

        const weekSales = recentOrders.data?.reduce((sum, o) => sum + Number(o.total_amount || 0), 0) || 0;

        result = {
          products: { active: totalProducts.count || 0 },
          orders: { total: totalOrders.count || 0, weekSales, weekCount: recentOrders.data?.length || 0 },
          users: { total: totalUsers.count || 0, newThisMonth: recentUsers.count || 0 },
          afterSales: { pending: pendingAfterSales.count || 0 },
          campaigns: { active: activeCampaigns.count || 0 }
        };
        break;
      }

      // ==================== 跨域操作(店铺经理协调) ====================
      case 'crossDomain.getStatus': {
        // 获取各领域状态汇总
        const [products, orders, campaigns, afterSales] = await Promise.all([
          supabase.from('products').select('id, is_active, stock_quantity'),
          supabase.from('orders').select('id, status').in('status', ['pending', 'processing']),
          supabase.from('marketing_campaigns').select('id, status').eq('status', 'active'),
          supabase.from('after_sales_requests').select('id, status').eq('status', 'pending')
        ]);

        result = {
          productAgent: {
            activeProducts: products.data?.filter(p => p.is_active).length || 0,
            lowStockAlerts: products.data?.filter(p => p.stock_quantity < 10).length || 0
          },
          marketingAgent: {
            activeCampaigns: campaigns.data?.length || 0
          },
          serviceAgent: {
            pendingOrders: orders.data?.length || 0,
            pendingAfterSales: afterSales.data?.length || 0
          }
        };
        break;
      }

      // ==================== Agent配置管理 ====================
      case 'agent.query': {
        let query = supabase.from('agent_settings').select('*');
        if (params.agentType) {
          query = query.eq('agent_type', params.agentType);
        }
        const { data, error } = await query.order('agent_type');
        if (error) throw error;
        result = { data, count: data?.length || 0 };
        break;
      }

      case 'agent.update': {
        const { agentType, isActive, autoExecuteEnabled, maxAutoAmount, responseStyle, tone, ...otherParams } = params;
        if (!agentType) throw new Error('缺少必需参数: agentType');
        
        const updates: Record<string, any> = { updated_at: new Date().toISOString() };
        if (isActive !== undefined) updates.is_active = isActive;
        if (autoExecuteEnabled !== undefined) updates.auto_execute_enabled = autoExecuteEnabled;
        if (maxAutoAmount !== undefined) updates.max_auto_amount = maxAutoAmount;
        if (responseStyle !== undefined) updates.response_style = responseStyle;
        if (tone !== undefined) updates.tone = tone;
        
        const { data, error } = await supabase
          .from('agent_settings')
          .update(updates)
          .eq('agent_type', agentType)
          .select()
          .single();
        if (error) throw error;
        result = { data, message: `${agentType} Agent 配置已更新` };
        break;
      }

      case 'agent.setAutoExecute': {
        const { agentType, enabled } = params;
        if (!agentType) throw new Error('缺少必需参数: agentType');
        if (enabled === undefined) throw new Error('缺少必需参数: enabled');
        
        const { data, error } = await supabase
          .from('agent_settings')
          .update({ auto_execute_enabled: enabled, updated_at: new Date().toISOString() })
          .eq('agent_type', agentType)
          .select()
          .single();
        if (error) throw error;
        result = { data, message: `${agentType} Agent 自动执行已${enabled ? '开启' : '关闭'}` };
        break;
      }

      case 'agent.setMaxAmount': {
        const { agentType, maxAmount } = params;
        if (!agentType) throw new Error('缺少必需参数: agentType');
        if (maxAmount === undefined) throw new Error('缺少必需参数: maxAmount');
        
        const { data, error } = await supabase
          .from('agent_settings')
          .update({ max_auto_amount: maxAmount, updated_at: new Date().toISOString() })
          .eq('agent_type', agentType)
          .select()
          .single();
        if (error) throw error;
        result = { data, message: `${agentType} Agent 自动执行额度已设为 ¥${maxAmount}` };
        break;
      }

      case 'agent.setGoals': {
        const { agentType, goals } = params;
        if (!agentType) throw new Error('缺少必需参数: agentType');
        if (!goals) throw new Error('缺少必需参数: goals');
        
        const { data, error } = await supabase
          .from('agent_settings')
          .update({ monthly_goals: goals, updated_at: new Date().toISOString() })
          .eq('agent_type', agentType)
          .select()
          .single();
        if (error) throw error;
        result = { data, message: `${agentType} Agent 目标已更新` };
        break;
      }

      case 'agent.setNotifications': {
        const { agentType, notifyOnInsights, notifyOnApprovals, notifyOnErrors } = params;
        if (!agentType) throw new Error('缺少必需参数: agentType');
        
        const updates: Record<string, any> = { updated_at: new Date().toISOString() };
        if (notifyOnInsights !== undefined) updates.notify_on_insights = notifyOnInsights;
        if (notifyOnApprovals !== undefined) updates.notify_on_approvals = notifyOnApprovals;
        if (notifyOnErrors !== undefined) updates.notify_on_errors = notifyOnErrors;
        
        const { data, error } = await supabase
          .from('agent_settings')
          .update(updates)
          .eq('agent_type', agentType)
          .select()
          .single();
        if (error) throw error;
        result = { data, message: `${agentType} Agent 通知设置已更新` };
        break;
      }

      case 'agent.setApprovalTypes': {
        const { agentType, approvalTypes } = params;
        if (!agentType) throw new Error('缺少必需参数: agentType');
        if (!Array.isArray(approvalTypes)) throw new Error('approvalTypes 必须是数组');
        
        const { data, error } = await supabase
          .from('agent_settings')
          .update({ requires_approval_types: approvalTypes, updated_at: new Date().toISOString() })
          .eq('agent_type', agentType)
          .select()
          .single();
        if (error) throw error;
        result = { data, message: `${agentType} Agent 审批类型已更新` };
        break;
      }

      // ==================== 目标管理 ====================
      case 'goal.query': {
        let query = supabase.from('goals').select('*');
        if (params.agentType) query = query.eq('agent_type', params.agentType);
        if (params.status) query = query.eq('status', params.status);
        if (params.assignedTo) query = query.eq('assigned_to', params.assignedTo);
        
        const { data, error } = await query.order('deadline', { ascending: true });
        if (error) throw error;
        result = { data, count: data?.length || 0 };
        break;
      }

      case 'goal.create': {
        const goalData = {
          title: params.title,
          description: params.description,
          target_value: params.targetValue,
          current_value: params.currentValue || 0,
          unit: params.unit || '元',
          deadline: params.deadline,
          priority: params.priority || 'medium',
          status: params.status || 'active',
          agent_type: params.agentType,
          assigned_by: params.assignedBy || '经理AI · 小管',
          assigned_to: params.assignedTo || params.agentType,
          created_by: user.id
        };
        
        const { data, error } = await supabase.from('goals').insert(goalData).select().single();
        if (error) throw error;
        result = { data, message: `目标 "${params.title}" 创建成功` };
        break;
      }

      case 'goal.update': {
        const { id, ...updates } = params;
        if (!id) throw new Error('缺少必需参数: id');
        
        const updateData: Record<string, any> = { updated_at: new Date().toISOString() };
        if (updates.title) updateData.title = updates.title;
        if (updates.description !== undefined) updateData.description = updates.description;
        if (updates.targetValue !== undefined) updateData.target_value = updates.targetValue;
        if (updates.currentValue !== undefined) updateData.current_value = updates.currentValue;
        if (updates.unit) updateData.unit = updates.unit;
        if (updates.deadline) updateData.deadline = updates.deadline;
        if (updates.priority) updateData.priority = updates.priority;
        if (updates.status) updateData.status = updates.status;
        
        const { data, error } = await supabase.from('goals').update(updateData).eq('id', id).select().single();
        if (error) throw error;
        result = { data, message: '目标已更新' };
        break;
      }

      case 'goal.updateProgress': {
        const { id, currentValue } = params;
        if (!id) throw new Error('缺少必需参数: id');
        if (currentValue === undefined) throw new Error('缺少必需参数: currentValue');
        
        const { data: goal } = await supabase.from('goals').select('target_value').eq('id', id).single();
        
        const updateData: Record<string, any> = { 
          current_value: currentValue,
          updated_at: new Date().toISOString()
        };
        
        // 自动标记为完成
        if (goal && currentValue >= goal.target_value) {
          updateData.status = 'completed';
        }
        
        const { data, error } = await supabase.from('goals').update(updateData).eq('id', id).select().single();
        if (error) throw error;
        result = { data, message: '目标进度已更新' };
        break;
      }

      case 'goal.delete': {
        const { id } = params;
        if (!id) throw new Error('缺少必需参数: id');
        
        const { error } = await supabase.from('goals').delete().eq('id', id);
        if (error) throw error;
        result = { message: '目标已删除' };
        break;
      }

      // ==================== 系统配置 ====================
      case 'system.getConfig': {
        // 获取系统配置信息
        result = {
          agents: {
            manager: { id: 'manager', name: '小管', role: '店铺经理', function: 'admin-operations' },
            product: { id: 'product', name: '小品', role: '商品经理', function: 'product-operations' },
            marketing: { id: 'marketing', name: '小营', role: '营销经理', function: 'marketing-operations' },
            service: { id: 'service', name: '小服', role: '客服经理', function: 'service-operations' }
          },
          version: '2.0.0',
          architecture: 'multi-agent-separated'
        };
        break;
      }

      default:
        throw new Error(`[Admin-Ops] 不支持的操作类型: ${operation}。请使用专属函数：product-operations(商品)、marketing-operations(营销)、service-operations(客服)`);
    }

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

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