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

// GET /api/orders/by-number/[orderNumber] - 根据订单号获取订单详情
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ orderNumber: string }> }
) {
  try {
    const { orderNumber } = await params;
    const client = getSupabaseClient();
    
    const { data, error } = await client
      .from('orders')
      .select('*')
      .eq('order_number', orderNumber)
      .single();
    
    if (error || !data) {
      return NextResponse.json(
        { error: '订单不存在' },
        { status: 404 }
      );
    }
    
    // 验证访问权限：已登录用户只能查看自己的订单
    const cookieStore = await cookies();
    const customerId = cookieStore.get('customer_id')?.value;
    const customerPhone = cookieStore.get('customer_phone')?.value;
    
    // 如果订单关联了客户，需要验证客户身份
    if (data.customer_id && data.customer_id !== customerId) {
      return NextResponse.json(
        { error: '无权访问此订单' },
        { status: 403 }
      );
    }
    
    // 如果订单没有关联客户但有联系电话，验证手机号
    if (!data.customer_id && customerPhone && data.contact_phone !== customerPhone) {
      return NextResponse.json(
        { error: '无权访问此订单' },
        { status: 403 }
      );
    }
    
    return NextResponse.json({ order: data });
  } catch (error) {
    console.error('Error:', error);
    return NextResponse.json(
      { error: '服务器错误' },
      { status: 500 }
    );
  }
}
