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

// POST /api/orders/[id]/mark-read - 客户标记订单消息已读
export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const cookieStore = await cookies();
    const customerId = cookieStore.get('customer_id')?.value;

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

    const client = getSupabaseClient();

    // 验证订单属于该客户
    const { data: order, error: orderError } = await client
      .from('orders')
      .select('id')
      .eq('id', id)
      .eq('customer_id', customerId)
      .single();

    if (orderError || !order) {
      return NextResponse.json(
        { error: '订单不存在' },
        { status: 404 }
      );
    }

    // 更新客户最后阅读时间
    const { error: updateError } = await client
      .from('orders')
      .update({ customer_last_read_at: new Date().toISOString() })
      .eq('id', id);

    if (updateError) {
      console.error('Error updating read time:', updateError);
      return NextResponse.json(
        { error: '更新失败' },
        { status: 500 }
      );
    }

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