/**
 * Conversation Messages API
 * GET - Get messages in conversation
 * POST - Send message to conversation
 * PATCH - Mark as read
 */

import { NextRequest, NextResponse } from 'next/server';
import {
  getMessages,
  sendMessage,
  markAsRead,
  editMessage,
  deleteMessage,
} from '@/lib/autonomy/messaging';

export const dynamic = 'force-dynamic';

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ conversationId: string }> }
) {
  try {
    const { conversationId } = await params;
    const { searchParams } = new URL(request.url);
    const userId = searchParams.get('userId');
    const limit = parseInt(searchParams.get('limit') || '50');
    const before = searchParams.get('before') || undefined;
    const after = searchParams.get('after') || undefined;

    if (!userId) {
      return NextResponse.json(
        { error: 'userId is required' },
        { status: 400 }
      );
    }

    const messages = await getMessages(conversationId, userId, { limit, before, after });

    return NextResponse.json({ messages });
  } catch (error: any) {
    console.error('Error fetching messages:', error);
    return NextResponse.json(
      { error: 'Failed to fetch messages', details: error.message },
      { status: 500 }
    );
  }
}

export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ conversationId: string }> }
) {
  try {
    const { conversationId } = await params;
    const body = await request.json();
    const { userId, content, contentType, attachments, replyToId } = body;

    if (!userId || !content) {
      return NextResponse.json(
        { error: 'userId and content are required' },
        { status: 400 }
      );
    }

    const messageId = await sendMessage(conversationId, userId, {
      content,
      contentType,
      attachments,
      replyToId,
    });

    return NextResponse.json({ messageId });
  } catch (error: any) {
    console.error('Error sending message:', error);
    return NextResponse.json(
      { error: 'Failed to send message', details: error.message },
      { status: 500 }
    );
  }
}

export async function PATCH(
  request: NextRequest,
  { params }: { params: Promise<{ conversationId: string }> }
) {
  try {
    const { conversationId } = await params;
    const body = await request.json();
    const { action, userId, messageId, content } = body;

    if (!userId) {
      return NextResponse.json(
        { error: 'userId is required' },
        { status: 400 }
      );
    }

    switch (action) {
      case 'read':
        await markAsRead(conversationId, userId, messageId);
        return NextResponse.json({ message: 'Marked as read' });

      case 'edit':
        if (!messageId || !content) {
          return NextResponse.json(
            { error: 'messageId and content are required for edit' },
            { status: 400 }
          );
        }
        await editMessage(messageId, userId, content);
        return NextResponse.json({ message: 'Message edited' });

      case 'delete':
        if (!messageId) {
          return NextResponse.json(
            { error: 'messageId is required for delete' },
            { status: 400 }
          );
        }
        await deleteMessage(messageId, userId);
        return NextResponse.json({ message: 'Message deleted' });

      default:
        return NextResponse.json(
          { error: 'Invalid action. Use: read, edit, delete' },
          { status: 400 }
        );
    }
  } catch (error: any) {
    console.error('Error updating message:', error);
    return NextResponse.json(
      { error: 'Failed to update', details: error.message },
      { status: 500 }
    );
  }
}
