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

// GET /api/admin/orders/unread-count - 获取管理员未读消息数量
export async function GET(request: NextRequest) {
  try {
    const cookieStore = await cookies();
    const adminId = cookieStore.get('admin_id')?.value;

    if (!adminId) {
      return NextResponse.json(
        { error: '请先登录' },
        { status: 401 }
      );
    }

    const client = getSupabaseClient();

    // 获取所有订单
    const { data: orders, error: ordersError } = await client
      .from('orders')
      .select('id, order_number, contact_name, admin_last_read_at');

    if (ordersError) {
      console.error('Error fetching orders:', ordersError);
      return NextResponse.json(
        { error: '获取订单失败' },
        { status: 500 }
      );
    }

    if (!orders || orders.length === 0) {
      return NextResponse.json({ 
        unreadOrders: [],
        totalUnread: 0 
      });
    }

    const orderIds = orders.map(o => o.id);
    const orderReadMap = new Map(orders.map(o => [o.id, { 
      lastRead: o.admin_last_read_at,
      orderNumber: o.order_number,
      contactName: o.contact_name
    }]));

    // 获取所有订单的消息，筛选出客户发送的
    const { data: messages, error: messagesError } = await client
      .from('order_messages')
      .select('order_id, created_at, sender_type')
      .in('order_id', orderIds)
      .eq('sender_type', 'customer');

    if (messagesError) {
      console.error('Error fetching messages:', messagesError);
      return NextResponse.json(
        { error: '获取消息失败' },
        { status: 500 }
      );
    }

    // 统计每个订单的未读消息数
    const unreadMap = new Map<string, number>();
    
    if (messages) {
      for (const msg of messages) {
        const orderInfo = orderReadMap.get(msg.order_id);
        if (!orderInfo) continue;
        
        // 如果从未阅读，或者消息时间晚于最后阅读时间
        if (!orderInfo.lastRead || new Date(msg.created_at) > new Date(orderInfo.lastRead)) {
          unreadMap.set(msg.order_id, (unreadMap.get(msg.order_id) || 0) + 1);
        }
      }
    }

    const unreadOrders = Array.from(unreadMap.entries()).map(([orderId, count]) => {
      const orderInfo = orderReadMap.get(orderId)!;
      return {
        orderId,
        orderNumber: orderInfo.orderNumber,
        contactName: orderInfo.contactName,
        unreadCount: count
      };
    });

    return NextResponse.json({
      unreadOrders,
      totalUnread: unreadOrders.reduce((sum, o) => sum + o.unreadCount, 0)
    });
  } catch (error) {
    console.error('Error:', error);
    return NextResponse.json(
      { error: '服务器错误' },
      { status: 500 }
    );
  }
}
