import { supabase } from "@/integrations/supabase/client";

/**
 * 查询所有品牌
 */
export async function queryBrands(params?: {
  keyword?: string;
  isActive?: boolean;
}) {
  try {
    let query = supabase.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;
    
    return {
      success: true,
      data: data || [],
      count: data?.length || 0
    };
  } catch (error) {
    console.error('查询品牌失败:', error);
    return {
      success: false,
      error: error instanceof Error ? error.message : '查询失败',
      data: []
    };
  }
}

/**
 * 根据品牌名称查询品牌及其商品
 */
export async function queryBrandWithProducts(brandName: string) {
  try {
    // 查询品牌
    const { data: brands, error: brandError } = await supabase
      .from('brands')
      .select('*')
      .ilike('name', `%${brandName}%`);
    
    if (brandError) throw brandError;
    
    if (!brands || brands.length === 0) {
      return {
        success: true,
        data: [],
        message: `未找到品牌: ${brandName}`
      };
    }

    // 查询每个品牌下的商品
    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) throw productError;
        
        return {
          ...brand,
          products: products || [],
          productCount: products?.length || 0
        };
      })
    );

    return {
      success: true,
      data: brandsWithProducts,
      count: brandsWithProducts.length,
      totalProducts: brandsWithProducts.reduce((sum, b) => sum + b.productCount, 0)
    };
  } catch (error) {
    console.error('查询品牌及商品失败:', error);
    return {
      success: false,
      error: error instanceof Error ? error.message : '查询失败',
      data: []
    };
  }
}

/**
 * 根据品牌ID查询品牌详情
 */
export async function queryBrandById(brandId: string) {
  try {
    const { data, error } = await supabase
      .from('brands')
      .select('*')
      .eq('id', brandId)
      .single();
    
    if (error) throw error;
    
    return {
      success: true,
      data
    };
  } catch (error) {
    console.error('查询品牌详情失败:', error);
    return {
      success: false,
      error: error instanceof Error ? error.message : '查询失败'
    };
  }
}
