import { NextRequest, NextResponse } from 'next/server';
import { getSupabaseClient } from '@/storage/database/supabase-client';
import { type Customer } from '@/storage/database/shared/schema';

// GET /api/admin/customers - 获取所有客户
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const search = searchParams.get('search');
    const page = parseInt(searchParams.get('page') || '1');
    const limit = parseInt(searchParams.get('limit') || '20');
    const offset = (page - 1) * limit;

    const client = getSupabaseClient();
    
    let query = client
      .from('customers')
      .select('*', { count: 'exact' })
      .order('created_at', { ascending: false });
    
    // 搜索
    if (search) {
      query = query.or(`name.ilike.%${search}%,phone.ilike.%${search}%,company.ilike.%${search}%`);
    }
    
    // 分页
    query = query.range(offset, offset + limit - 1);
    
    const { data, error, count } = await query;
    
    if (error) {
      console.error('Error fetching customers:', error);
      return NextResponse.json(
        { error: '获取客户失败' },
        { status: 500 }
      );
    }
    
    // 获取每个客户的订单数量
    const customersWithOrders = await Promise.all(
      (data as Customer[]).map(async (customer) => {
        const { count: orderCount } = await client
          .from('orders')
          .select('*', { count: 'exact', head: true })
          .eq('customer_id', customer.id);
        
        return {
          ...customer,
          orderCount: orderCount || 0,
        };
      })
    );
    
    return NextResponse.json({
      customers: customersWithOrders,
      total: count || 0,
      page,
      limit,
      totalPages: Math.ceil((count || 0) / limit),
    });
  } catch (error) {
    console.error('Error:', error);
    return NextResponse.json(
      { error: '服务器错误' },
      { status: 500 }
    );
  }
}
