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

// GET /api/orders - 获取订单列表
export async function GET(request: NextRequest) {
  try {
    const client = getSupabaseClient();
    
    const cookieStore = await cookies();
    const customerId = cookieStore.get('customer_id')?.value;
    const customerPhone = cookieStore.get('customer_phone')?.value;
    
    const { searchParams } = new URL(request.url);
    const phone = searchParams.get('phone');
    
    let query = client
      .from('orders')
      .select('*')
      .order('created_at', { ascending: false });
    
    // 如果用户已登录，按客户ID查询
    if (customerId) {
      query = query.eq('customer_id', customerId);
    } else if (phone) {
      // 未登录时，按手机号查询
      query = query.eq('contact_phone', phone);
    } else if (customerPhone) {
      // 如果有登录记录但cookie中只有手机号
      query = query.eq('contact_phone', customerPhone);
    } else {
      // 没有任何查询条件，返回空
      return NextResponse.json({ orders: [] });
    }
    
    const { data, error } = await query;
    
    if (error) {
      console.error('Error fetching orders:', error);
      return NextResponse.json(
        { error: '获取订单列表失败' },
        { status: 500 }
      );
    }
    
    return NextResponse.json({ orders: data as Order[] });
  } catch (error) {
    console.error('Error:', error);
    return NextResponse.json(
      { error: '服务器错误' },
      { status: 500 }
    );
  }
}

// POST /api/orders - 创建新订单
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    
    // 验证请求数据
    const validationResult = insertOrderSchema.safeParse(body);
    if (!validationResult.success) {
      return NextResponse.json(
        { error: '数据验证失败', details: validationResult.error.issues },
        { status: 400 }
      );
    }
    
    const { contactName, contactPhone, contactEmail, originCity, destinationCity, customsCity, notes } = validationResult.data;
    
    const client = getSupabaseClient();
    
    // 获取当前登录用户
    const cookieStore = await cookies();
    const customerId = cookieStore.get('customer_id')?.value;
    
    // 生成递增订单号
    // 获取当前最大订单号
    const { data: maxOrder } = await client
      .from('orders')
      .select('order_number')
      .order('order_number', { ascending: false })
      .limit(1)
      .single();
    
    let nextOrderNumber = '001';
    if (maxOrder?.order_number) {
      const currentNum = parseInt(maxOrder.order_number, 10);
      nextOrderNumber = String(currentNum + 1).padStart(3, '0');
    }
    
    // 使用 snake_case 字段名插入数据库
    const { data, error } = await client
      .from('orders')
      .insert({
        order_number: nextOrderNumber,
        customer_id: customerId || null,
        contact_name: contactName,
        contact_phone: contactPhone,
        contact_email: contactEmail || null,
        origin_city: originCity,
        destination_city: destinationCity,
        customs_city: customsCity,
        notes: notes || null,
        status: '新询价',
      })
      .select()
      .single();
    
    if (error) {
      console.error('Error creating 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 }
    );
  }
}
