import { NextRequest, NextResponse } from 'next/server';
import { getSupabaseClient } from '@/storage/database/supabase-client';
import { ORDER_STATUS, type Order } from '@/storage/database/shared/schema';

// POST /api/orders/[id]/confirm - 客户确认订单
export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    
    const client = getSupabaseClient();
    
    // 先检查订单当前状态
    const { data: existingOrder, error: fetchError } = await client
      .from('orders')
      .select('id, status')
      .eq('id', id)
      .single();
    
    if (fetchError || !existingOrder) {
      return NextResponse.json(
        { error: '订单不存在' },
        { status: 404 }
      );
    }
    
    // 只有待确认状态的订单可以确认
    if (existingOrder.status !== ORDER_STATUS.PENDING_CONFIRM) {
      return NextResponse.json(
        { error: '当前订单状态不允许确认', currentStatus: existingOrder.status },
        { status: 400 }
      );
    }
    
    // 更新订单状态为确认
    const { data, error } = await client
      .from('orders')
      .update({ 
        status: ORDER_STATUS.CONFIRMED,
        updated_at: new Date().toISOString()
      })
      .eq('id', id)
      .select()
      .single();
    
    if (error) {
      console.error('Error confirming order:', error);
      return NextResponse.json(
        { error: '确认订单失败' },
        { status: 500 }
      );
    }
    
    return NextResponse.json({ 
      success: true, 
      order: data as Order,
      message: '订单已确认'
    });
  } catch (error) {
    console.error('Error:', error);
    return NextResponse.json(
      { error: '服务器错误' },
      { status: 500 }
    );
  }
}
