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

// GET /api/admin/orders/[id]/messages - 获取订单消息
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    
    const client = getSupabaseClient();
    
    const { data, error } = await client
      .from('order_messages')
      .select('*')
      .eq('order_id', id)
      .order('created_at', { ascending: true });
    
    if (error) {
      console.error('Error fetching messages:', error);
      return NextResponse.json(
        { error: '获取消息失败' },
        { status: 500 }
      );
    }
    
    return NextResponse.json({ messages: data as OrderMessage[] });
  } catch (error) {
    console.error('Error:', error);
    return NextResponse.json(
      { error: '服务器错误' },
      { status: 500 }
    );
  }
}

// POST /api/admin/orders/[id]/messages - 发送消息
export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const body = await request.json();
    
    // 验证数据
    const messageData = {
      orderId: id,
      messageType: body.messageType || 'text',
      content: body.content,
      fileUrl: body.fileUrl,
      fileName: body.fileName,
      fileSize: body.fileSize,
    };
    
    const validationResult = createMessageSchema.safeParse(messageData);
    if (!validationResult.success) {
      return NextResponse.json(
        { error: '数据验证失败', details: validationResult.error.issues },
        { status: 400 }
      );
    }
    
    // 获取管理员信息
    const adminId = request.headers.get('cookie')
      ?.split(';')
      .find(c => c.trim().startsWith('admin_id='))
      ?.split('=')[1];
    
    const adminName = request.headers.get('cookie')
      ?.split(';')
      .find(c => c.trim().startsWith('admin_name='))
      ?.split('=')[1];
    
    const client = getSupabaseClient();
    
    const { data, error } = await client
      .from('order_messages')
      .insert({
        order_id: id,
        sender_type: 'admin',
        sender_id: adminId || 'unknown',
        sender_name: adminName ? decodeURIComponent(adminName) : '客服',
        message_type: validationResult.data.messageType,
        content: validationResult.data.content,
        file_url: validationResult.data.fileUrl,
        file_name: validationResult.data.fileName,
        file_size: validationResult.data.fileSize,
      })
      .select()
      .single();
    
    if (error) {
      console.error('Error sending message:', error);
      return NextResponse.json(
        { error: '发送消息失败' },
        { status: 500 }
      );
    }
    
    // 更新管理员最后阅读时间（发送消息意味着已读）
    await client
      .from('orders')
      .update({ admin_last_read_at: new Date().toISOString() })
      .eq('id', id);
    
    return NextResponse.json({ 
      success: true, 
      message: data as OrderMessage 
    });
  } catch (error) {
    console.error('Error:', error);
    return NextResponse.json(
      { error: '服务器错误' },
      { status: 500 }
    );
  }
}
