import { NextResponse } from 'next/server';
import { getSupabaseClient } from '@/storage/database/supabase-client';

// GET /api/admin/stats - 获取统计数据
export async function GET() {
  try {
    const client = getSupabaseClient();
    
    // 获取订单统计
    const { data: orders } = await client
      .from('orders')
      .select('status, created_at');
    
    // 获取客户统计
    const { count: customerCount } = await client
      .from('customers')
      .select('*', { count: 'exact', head: true });
    
    // 获取消息统计
    const { count: unreadMessages } = await client
      .from('order_messages')
      .select('*', { count: 'exact', head: true })
      .eq('sender_type', 'customer');
    
    // 计算各状态订单数量
    const statusCounts: Record<string, number> = {
      '新询价': 0,
      '待确认': 0,
      '装车方案设计中': 0,
      '确认': 0,
      '运输中': 0,
      '清关未完成': 0,
      '配送完成': 0,
    };
    
    let todayOrders = 0;
    let weekOrders = 0;
    let monthOrders = 0;
    
    const now = new Date();
    const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());
    const weekStart = new Date(todayStart.getTime() - 7 * 24 * 60 * 60 * 1000);
    const monthStart = new Date(todayStart.getTime() - 30 * 24 * 60 * 60 * 1000);
    
    orders?.forEach(order => {
      // 状态统计
      if (statusCounts[order.status] !== undefined) {
        statusCounts[order.status]++;
      }
      
      // 时间统计
      const createdAt = new Date(order.created_at);
      if (createdAt >= todayStart) todayOrders++;
      if (createdAt >= weekStart) weekOrders++;
      if (createdAt >= monthStart) monthOrders++;
    });
    
    return NextResponse.json({
      orders: {
        total: orders?.length || 0,
        today: todayOrders,
        week: weekOrders,
        month: monthOrders,
        byStatus: statusCounts,
      },
      customers: {
        total: customerCount || 0,
      },
      messages: {
        total: unreadMessages || 0,
      },
    });
  } catch (error) {
    console.error('Error:', error);
    return NextResponse.json(
      { error: '获取统计数据失败' },
      { status: 500 }
    );
  }
}
