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

// POST /api/orders/[id]/messages - 发送消息
export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id: orderId } = await params;
    const cookieStore = await cookies();
    const customerId = cookieStore.get('customer_id')?.value;
    const customerName = cookieStore.get('customer_name')?.value;

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

    const body = await request.json();
    
    // 验证请求数据
    const validationResult = createMessageSchema.safeParse({
      orderId,
      ...body,
    });
    
    if (!validationResult.success) {
      return NextResponse.json(
        { error: '数据验证失败', details: validationResult.error.issues },
        { status: 400 }
      );
    }

    const { messageType, content, fileUrl, fileName, fileSize } = validationResult.data;

    // 验证消息内容
    if (messageType === 'text' && (!content || content.trim() === '')) {
      return NextResponse.json(
        { error: '消息内容不能为空' },
        { status: 400 }
      );
    }

    if ((messageType === 'image' || messageType === 'file') && !fileUrl) {
      return NextResponse.json(
        { error: '请上传文件' },
        { status: 400 }
      );
    }

    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 }
      );
    }

    // 获取用户名
    let senderName = customerName;
    if (!senderName) {
      const { data: customer } = await client
        .from('customers')
        .select('name')
        .eq('id', customerId)
        .single();
      senderName = customer?.name || '用户';
    }

    // 创建消息
    const { data: message, error } = await client
      .from('order_messages')
      .insert({
        order_id: orderId,
        sender_type: 'customer',
        sender_id: customerId,
        sender_name: senderName,
        message_type: messageType,
        content: content || null,
        file_url: fileUrl || null,
        file_name: fileName || null,
        file_size: fileSize || null,
      })
      .select()
      .single();

    if (error) {
      console.error('Error creating message:', error);
      return NextResponse.json(
        { error: '发送消息失败' },
        { status: 500 }
      );
    }

    // 更新客户最后阅读时间（发送消息意味着已读）
    await client
      .from('orders')
      .update({ customer_last_read_at: new Date().toISOString() })
      .eq('id', orderId);

    return NextResponse.json({
      success: true,
      message,
    });
  } catch (error) {
    console.error('Error:', error);
    return NextResponse.json(
      { error: '服务器错误' },
      { status: 500 }
    );
  }
}
