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

// GET /api/orders/[id]/messages - 获取订单消息列表
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id: orderId } = await params;
    const cookieStore = await cookies();
    const customerId = cookieStore.get('customer_id')?.value;

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

    const client = getSupabaseClient();

    // 验证订单归属
    const { data: order, error: orderError } = await client
      .from('orders')
      .select('id, customer_id')
      .eq('id', orderId)
      .single();

    if (orderError || !order) {
      return NextResponse.json(
        { error: '订单不存在' },
        { status: 404 }
      );
    }

    // 验证用户权限（订单属于该用户）
    if (order.customer_id !== customerId) {
      return NextResponse.json(
        { error: '无权访问此订单' },
        { status: 403 }
      );
    }

    // 获取消息列表
    const { data: messages, error } = await client
      .from('order_messages')
      .select('*')
      .eq('order_id', orderId)
      .order('created_at', { ascending: true });

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

    return NextResponse.json({ messages: messages || [] });
  } catch (error) {
    console.error('Error:', error);
    return NextResponse.json(
      { error: '服务器错误' },
      { status: 500 }
    );
  }
}
