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

// GET /api/orders/unread-count - 获取客户未读消息数量
export async function GET(request: NextRequest) {
  try {
    const cookieStore = await cookies();
    const customerId = cookieStore.get('customer_id')?.value;

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

    const client = getSupabaseClient();

    // 获取该客户所有订单
    const { data: orders, error: ordersError } = await client
      .from('orders')
      .select('id, customer_last_read_at')
      .eq('customer_id', customerId);

    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, o.customer_last_read_at]));

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

    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 lastRead = orderReadMap.get(msg.order_id);
        // 如果从未阅读，或者消息时间晚于最后阅读时间
        if (!lastRead || new Date(msg.created_at) > new Date(lastRead)) {
          unreadMap.set(msg.order_id, (unreadMap.get(msg.order_id) || 0) + 1);
        }
      }
    }

    const unreadOrders = Array.from(unreadMap.entries()).map(([orderId, count]) => ({
      orderId,
      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 }
    );
  }
}
