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

// GET /api/admin/orders - 获取所有订单（支持筛选）
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const status = searchParams.get('status');
    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('orders')
      .select('*', { count: 'exact' })
      .order('created_at', { ascending: false });
    
    // 状态筛选
    if (status && status !== 'all') {
      query = query.eq('status', status);
    }
    
    // 搜索
    if (search) {
      query = query.or(`contact_name.ilike.%${search}%,contact_phone.ilike.%${search}%,origin_city.ilike.%${search}%,destination_city.ilike.%${search}%`);
    }
    
    // 分页
    query = query.range(offset, offset + limit - 1);
    
    const { data, error, count } = await query;
    
    if (error) {
      console.error('Error fetching orders:', error);
      return NextResponse.json(
        { error: '获取订单失败' },
        { status: 500 }
      );
    }
    
    return NextResponse.json({
      orders: data as Order[],
      total: count || 0,
      page,
      limit,
      totalPages: Math.ceil((count || 0) / limit),
    });
  } catch (error) {
    console.error('Error:', error);
    return NextResponse.json(
      { error: '服务器错误' },
      { status: 500 }
    );
  }
}
