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('未授权访问');
    }

    // 使用 service_role key 绕过 RLS，在函数内部做权限校验
    const supabaseClient = createClient(
      Deno.env.get('SUPABASE_URL') ?? '',
      Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? '',
      { auth: { persistSession: false, autoRefreshToken: false } }
    );

    // 用 auth header 单独验证用户身份
    const authResponse = await fetch(
      `${Deno.env.get('SUPABASE_URL')}/auth/v1/user`,
      { headers: { Authorization: authHeader, apikey: Deno.env.get('SUPABASE_ANON_KEY') ?? '' } }
    );
    const authJson = await authResponse.json();
    const userId = authJson?.id;
    if (!userId) throw new Error('用户未认证');

    // 验证管理员权限
    const { data: profile } = await supabaseClient
      .from('profiles')
      .select('role')
      .eq('user_id', userId)
      .single();

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

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

    let result;

    switch (operation) {
      // ==================== 产品管理 ====================
      case 'product.query': {
        let query = supabaseClient.from('products').select('*');
        if (params.keyword) {
          query = query.or(`name.ilike.%${params.keyword}%,description.ilike.%${params.keyword}%`);
        }
        if (params.category) query = query.eq('category', params.category);
        if (params.brand) query = query.eq('brand', params.brand);
        if (params.minPrice) query = query.gte('price', params.minPrice);
        if (params.maxPrice) query = query.lte('price', params.maxPrice);
        if (params.isActive !== undefined) query = query.eq('is_active', params.isActive);
        if (params.isHot !== undefined) query = query.eq('is_hot', params.isHot);
        if (params.isRecommended !== undefined) query = query.eq('is_recommended', params.isRecommended);
        if (params.lowStock) query = query.lte('stock_quantity', params.lowStock);
        
        const { data, error } = await query.order('created_at', { ascending: false });
        if (error) throw error;
        result = { data, count: data?.length || 0 };
        break;
      }

      case 'product.create': {
        const productData = {
          name: params.name,
          description: params.description,
          price: params.price,
          category: params.category,
          brand: params.brand,
          stock_quantity: params.stock_quantity || 0,
          image_url: params.image_url,
          images: params.images,
          specifications: params.specifications,
          is_active: params.is_active !== false,
          is_hot: params.is_hot || false,
          is_recommended: params.is_recommended || false,
          release_date: params.release_date,
          ram: params.ram,
          pixel: params.pixel,
          battery_capacity: params.battery_capacity,
          core_processor: params.core_processor,
          screen_refresh_rate: params.screen_refresh_rate,
        };
        
        const { data, error } = await supabaseClient.from('products').insert(productData).select().single();
        if (error) throw error;
        result = { data, message: `产品 "${params.name}" 创建成功` };
        break;
      }

      case 'product.update': {
        const { id, ...updates } = params;
        updates.updated_at = new Date().toISOString();
        const { data, error } = await supabaseClient.from('products').update(updates).eq('id', id).select().single();
        if (error) throw error;
        result = { data, message: '产品更新成功' };
        break;
      }

      case 'product.delete': {
        const { error } = await supabaseClient.from('products').delete().eq('id', params.id);
        if (error) throw error;
        result = { message: '产品删除成功' };
        break;
      }

      case 'product.updateStock': {
        const { data, error } = await supabaseClient.from('products')
          .update({ stock_quantity: params.stock_quantity, updated_at: new Date().toISOString() })
          .eq('id', params.id)
          .select().single();
        if (error) throw error;
        result = { data, message: '库存更新成功' };
        break;
      }

      case 'product.batchUpdateStock': {
        const updates = params.items.map(async (item: { id: string; stock_quantity: number }) => {
          return supabaseClient.from('products')
            .update({ stock_quantity: item.stock_quantity, updated_at: new Date().toISOString() })
            .eq('id', item.id);
        });
        await Promise.all(updates);
        result = { message: `批量更新${params.items.length}个商品库存成功` };
        break;
      }

      case 'product.updatePrice': {
        const { data, error } = await supabaseClient.from('products')
          .update({ price: params.price, updated_at: new Date().toISOString() })
          .eq('id', params.id)
          .select().single();
        if (error) throw error;
        result = { data, message: '价格更新成功' };
        break;
      }

      case 'product.batchUpdatePrice': {
        const updates = params.items.map(async (item: { id: string; price: number }) => {
          return supabaseClient.from('products')
            .update({ price: item.price, updated_at: new Date().toISOString() })
            .eq('id', item.id);
        });
        await Promise.all(updates);
        result = { message: `批量更新${params.items.length}个商品价格成功` };
        break;
      }

      case 'product.toggleStatus': {
        const { data, error } = await supabaseClient.from('products')
          .update({ is_active: params.is_active, updated_at: new Date().toISOString() })
          .eq('id', params.id)
          .select().single();
        if (error) throw error;
        result = { data, message: params.is_active ? '商品已上架' : '商品已下架' };
        break;
      }

      case 'product.setRecommended': {
        const { data, error } = await supabaseClient.from('products')
          .update({ is_recommended: params.is_recommended, updated_at: new Date().toISOString() })
          .eq('id', params.id)
          .select().single();
        if (error) throw error;
        result = { data, message: params.is_recommended ? '已设为推荐商品' : '已取消推荐' };
        break;
      }

      case 'product.setHot': {
        const { data, error } = await supabaseClient.from('products')
          .update({ is_hot: params.is_hot, updated_at: new Date().toISOString() })
          .eq('id', params.id)
          .select().single();
        if (error) throw error;
        result = { data, message: params.is_hot ? '已设为热销商品' : '已取消热销' };
        break;
      }

      // ==================== 分类管理 ====================
      case 'category.query': {
        let query = supabaseClient.from('categories').select('*');
        if (params.parentId !== undefined) {
          query = params.parentId === null 
            ? query.is('parent_id', null)
            : query.eq('parent_id', params.parentId);
        }
        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 'category.create': {
        const { data, error } = await supabaseClient.from('categories').insert(params).select().single();
        if (error) throw error;
        result = { data, message: `分类 "${params.name}" 创建成功` };
        break;
      }

      case 'category.update': {
        const { id, ...updates } = params;
        updates.updated_at = new Date().toISOString();
        const { data, error } = await supabaseClient.from('categories').update(updates).eq('id', id).select().single();
        if (error) throw error;
        result = { data, message: '分类更新成功' };
        break;
      }

      case 'category.delete': {
        const { error } = await supabaseClient.from('categories').delete().eq('id', params.id);
        if (error) throw error;
        result = { message: '分类删除成功' };
        break;
      }

      // ==================== 品牌管理 ====================
      case 'brand.query': {
        let query = supabaseClient.from('brands').select('*');
        if (params.keyword) {
          query = query.ilike('name', `%${params.keyword}%`);
        }
        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 'brand.queryWithProducts': {
        const { data: brands, error: brandError } = await supabaseClient
          .from('brands')
          .select('*')
          .ilike('name', `%${params.brandName}%`);

        if (brandError) throw brandError;

        if (!brands || brands.length === 0) {
          result = { data: [], message: `未找到品牌: ${params.brandName}` };
          break;
        }

        const brandsWithProducts = await Promise.all(
          brands.map(async (brand) => {
            const { data: products } = await supabaseClient
              .from('products')
              .select('*')
              .eq('brand', brand.name)
              .order('created_at', { ascending: false });
            
            return {
              ...brand,
              products: products || [],
              productCount: products?.length || 0
            };
          })
        );

        result = { 
          data: brandsWithProducts,
          count: brandsWithProducts.length,
          totalProducts: brandsWithProducts.reduce((sum, b) => sum + b.productCount, 0)
        };
        break;
      }

      case 'brand.create': {
        const { data, error } = await supabaseClient.from('brands').insert(params).select().single();
        if (error) throw error;
        result = { data, message: `品牌 "${params.name}" 创建成功` };
        break;
      }

      case 'brand.update': {
        const { id, ...updates } = params;
        updates.updated_at = new Date().toISOString();
        const { data, error } = await supabaseClient.from('brands').update(updates).eq('id', id).select().single();
        if (error) throw error;
        result = { data, message: '品牌更新成功' };
        break;
      }

      case 'brand.delete': {
        const { error } = await supabaseClient.from('brands').delete().eq('id', params.id);
        if (error) throw error;
        result = { message: '品牌删除成功' };
        break;
      }

      // ==================== 商品分析 ====================
      case 'analytics.products': {
        const { data, error } = await supabaseClient.from('products')
          .select('id, name, price, stock_quantity, category, brand, is_active, monthly_sales, monthly_browse, praise_rate')
          .limit(params.limit || 100);
        if (error) throw error;
        
        const lowStockProducts = data?.filter(p => p.stock_quantity < 10) || [];
        const topSelling = [...(data || [])].sort((a, b) => (b.monthly_sales || 0) - (a.monthly_sales || 0)).slice(0, 10);
        
        result = { 
          data, 
          count: data?.length || 0,
          lowStockCount: lowStockProducts.length,
          lowStockProducts,
          topSelling
        };
        break;
      }

      case 'analytics.inventory': {
        const { data, error } = await supabaseClient.from('products')
          .select('id, name, stock_quantity, category, brand, price');
        if (error) throw error;
        
        const totalStock = data?.reduce((sum, p) => sum + (p.stock_quantity || 0), 0) || 0;
        const totalValue = data?.reduce((sum, p) => sum + (p.stock_quantity || 0) * (p.price || 0), 0) || 0;
        const lowStock = data?.filter(p => p.stock_quantity < (params.threshold || 10)) || [];
        const outOfStock = data?.filter(p => p.stock_quantity === 0) || [];
        
        result = {
          totalProducts: data?.length || 0,
          totalStock,
          totalValue,
          lowStockCount: lowStock.length,
          outOfStockCount: outOfStock.length,
          lowStockProducts: lowStock,
          outOfStockProducts: outOfStock
        };
        break;
      }

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

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

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