/**
 * Internal Messaging API
 * GET - Get user's conversations
 * POST - Create conversation or send message
 */

import { NextRequest, NextResponse } from 'next/server';
import {
  getUserConversations,
  getOrCreateDirectConversation,
  createGroupConversation,
  createChannel,
  sendMessage,
} from '@/lib/autonomy/messaging';

export const dynamic = 'force-dynamic';

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const userId = searchParams.get('userId');

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

    const conversations = await getUserConversations(userId);

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

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { action, userId } = body;

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

    switch (action) {
      case 'direct': {
        const { targetUserId } = body;
        if (!targetUserId) {
          return NextResponse.json(
            { error: 'targetUserId is required for direct message' },
            { status: 400 }
          );
        }
        const conversationId = await getOrCreateDirectConversation(userId, targetUserId);
        return NextResponse.json({ conversationId });
      }

      case 'group': {
        const { name, memberIds, description } = body;
        if (!name || !memberIds?.length) {
          return NextResponse.json(
            { error: 'name and memberIds are required for group' },
            { status: 400 }
          );
        }
        const conversationId = await createGroupConversation(name, userId, memberIds, description);
        return NextResponse.json({ conversationId });
      }

      case 'channel': {
        const { name, description } = body;
        if (!name) {
          return NextResponse.json(
            { error: 'name is required for channel' },
            { status: 400 }
          );
        }
        const conversationId = await createChannel(name, userId, description);
        return NextResponse.json({ conversationId });
      }

      case 'send': {
        const { conversationId, content, contentType, attachments, replyToId } = body;
        if (!conversationId || !content) {
          return NextResponse.json(
            { error: 'conversationId and content are required' },
            { status: 400 }
          );
        }
        const messageId = await sendMessage(conversationId, userId, {
          content,
          contentType,
          attachments,
          replyToId,
        });
        return NextResponse.json({ messageId });
      }

      default:
        return NextResponse.json(
          { error: 'Invalid action. Use: direct, group, channel, send' },
          { status: 400 }
        );
    }
  } catch (error: any) {
    console.error('Error in messaging API:', error);
    return NextResponse.json(
      { error: 'Failed to process request', details: error.message },
      { status: 500 }
    );
  }
}
