import { createClient } from 'https://esm.sh/@supabase/supabase-js@2.57.4';

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

interface BrandQueryRequest {
  action: 'list' | 'search' | 'getById' | 'getWithProducts';
  keyword?: string;
  brandId?: string;
  brandName?: string;
  isActive?: boolean;
}

Deno.serve(async (req) => {
  // Handle CORS preflight requests
  if (req.method === 'OPTIONS') {
    return new Response(null, { headers: corsHeaders });
  }

  try {
    const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
    const supabaseKey = Deno.env.get('SUPABASE_ANON_KEY')!;
    const supabase = createClient(supabaseUrl, supabaseKey);

    const requestData: BrandQueryRequest = await req.json();
    const { action, keyword, brandId, brandName, isActive } = requestData;

    console.log('Brand query request:', { action, keyword, brandId, brandName, isActive });

    switch (action) {
      case 'list': {
        // 查询所有品牌
        let query = supabase.from('brands').select('*');
        
        if (keyword) {
          query = query.ilike('name', `%${keyword}%`);
        }
        
        if (isActive !== undefined) {
          query = query.eq('is_active', isActive);
        }
        
        const { data, error } = await query.order('display_order', { ascending: true });
        
        if (error) throw error;
        
        return new Response(
          JSON.stringify({
            success: true,
            data: data || [],
            count: data?.length || 0
          }),
          { headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
        );
      }

      case 'search': {
        // 根据关键词搜索品牌（支持中英文别名，从数据库读取）
        if (!keyword) {
          return new Response(
            JSON.stringify({ success: false, error: '缺少关键词参数' }),
            { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
          );
        }

        const normalizedKeyword = keyword.toLowerCase().trim();
        
        // 搜索品牌名称或别名数组中包含关键词的品牌
        // 使用 PostgreSQL 数组操作符和 ilike 进行搜索
        const { data, error } = await supabase
          .from('brands')
          .select('*')
          .eq('is_active', true)
          .or(`name.ilike.%${keyword}%,aliases.cs.{${normalizedKeyword}}`)
          .order('display_order', { ascending: true });
        
        if (error) throw error;
        
        return new Response(
          JSON.stringify({
            success: true,
            data: data || [],
            count: data?.length || 0
          }),
          { headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
        );
      }

      case 'getById': {
        // 根据ID查询品牌详情
        if (!brandId) {
          return new Response(
            JSON.stringify({ success: false, error: '缺少品牌ID参数' }),
            { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
          );
        }

        const { data, error } = await supabase
          .from('brands')
          .select('*')
          .eq('id', brandId)
          .single();
        
        if (error) throw error;
        
        return new Response(
          JSON.stringify({
            success: true,
            data
          }),
          { headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
        );
      }

      case 'getWithProducts': {
        // 查询品牌及其商品
        if (!brandName) {
          return new Response(
            JSON.stringify({ success: false, error: '缺少品牌名称参数' }),
            { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
          );
        }

        // 查询品牌
        const { data: brands, error: brandError } = await supabase
          .from('brands')
          .select('*')
          .ilike('name', `%${brandName}%`);
        
        if (brandError) throw brandError;
        
        if (!brands || brands.length === 0) {
          return new Response(
            JSON.stringify({
              success: true,
              data: [],
              message: `未找到品牌: ${brandName}`
            }),
            { headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
          );
        }

        // 查询每个品牌下的商品
        const brandsWithProducts = await Promise.all(
          brands.map(async (brand) => {
            const { data: products, error: productError } = await supabase
              .from('products')
              .select('*')
              .eq('brand', brand.name)
              .eq('is_active', true)
              .order('created_at', { ascending: false });
            
            if (productError) {
              console.error('查询商品失败:', productError);
              return {
                ...brand,
                products: [],
                productCount: 0
              };
            }
            
            return {
              ...brand,
              products: products || [],
              productCount: products?.length || 0
            };
          })
        );

        return new Response(
          JSON.stringify({
            success: true,
            data: brandsWithProducts,
            count: brandsWithProducts.length,
            totalProducts: brandsWithProducts.reduce((sum, b) => sum + b.productCount, 0)
          }),
          { headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
        );
      }

      default:
        return new Response(
          JSON.stringify({ success: false, error: '不支持的操作' }),
          { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
        );
    }
  } catch (error) {
    console.error('品牌查询失败:', error);
    return new Response(
      JSON.stringify({
        success: false,
        error: (error instanceof Error ? error.message : '查询失败')
      }),
      { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
    );
  }
});
