/**
 * 分销消息API
 * 用于WebSocket轮询获取实时消息
 */

import { NextRequest, NextResponse } from 'next/server';
import { getMessages, clearMessages } from '@/lib/modules/distribution/websocket';

// GET: 获取用户消息
export async function GET(req: NextRequest) {
  const { searchParams } = new URL(req.url);
  const userId = searchParams.get('userId');
  const since = searchParams.get('since');

  if (!userId) {
    return NextResponse.json({ error: '缺少用户ID' }, { status: 400 });
  }

  try {
    const messages = getMessages(userId, since || undefined);
    
    return NextResponse.json({
      success: true,
      messages,
      count: messages.length,
    });
  } catch (error) {
    console.error('[MessagesAPI] 获取消息失败:', error);
    return NextResponse.json({ error: '获取消息失败' }, { status: 500 });
  }
}

// POST: 标记消息已读
export async function POST(req: NextRequest) {
  try {
    const body = await req.json();
    const { userId, messageIds } = body;

    if (!userId || !messageIds || !Array.isArray(messageIds)) {
      return NextResponse.json({ error: '参数错误' }, { status: 400 });
    }

    clearMessages(userId, messageIds);

    return NextResponse.json({
      success: true,
      message: '消息已标记为已读',
    });
  } catch (error) {
    console.error('[MessagesAPI] 标记已读失败:', error);
    return NextResponse.json({ error: '操作失败' }, { status: 500 });
  }
}
