import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { prisma } from '@/lib/prisma';

export async function GET(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions);
    
    if (!session?.user?.email) {
      return NextResponse.json(
        { error: 'Unauthorized' },
        { status: 401 }
      );
    }

    const user = await prisma.user.findUnique({
      where: { email: session.user.email },
      include: {
        profile: true
      }
    });

    if (!user) {
      return NextResponse.json(
        { error: 'User not found' },
        { status: 404 }
      );
    }

    const { searchParams } = new URL(req.url);
    const page = parseInt(searchParams.get('page') || '1');
    const limit = parseInt(searchParams.get('limit') || '20');
    const contactId = searchParams.get('contactId');
    const projectId = searchParams.get('projectId');

    const skip = (page - 1) * limit;

    const where: any = {
      OR: [
        { senderId: user.id },
        { receiverId: user.id }
      ]
    };

    if (contactId) {
      where.OR = [
        { senderId: user.id, receiverId: contactId },
        { senderId: contactId, receiverId: user.id }
      ];
    }

    if (projectId) {
      where.projectId = projectId;
    }

    const [messages, total] = await Promise.all([
      prisma.message.findMany({
        where,
        include: {
          sender: {
            include: {
              profile: true
            }
          },
          receiver: {
            include: {
              profile: true
            }
          },
          project: {
            select: {
              id: true,
              title: true
            }
          }
        },
        orderBy: { createdAt: 'desc' },
        skip,
        take: limit
      }),
      prisma.message.count({ where })
    ]);

    return NextResponse.json({
      success: true,
      data: {
        messages,
        pagination: {
          page,
          limit,
          total,
          totalPages: Math.ceil(total / limit),
          hasNext: page * limit < total,
          hasPrev: page > 1
        }
      }
    });

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

export async function POST(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions);
    
    if (!session?.user?.email) {
      return NextResponse.json(
        { error: 'Unauthorized' },
        { status: 401 }
      );
    }

    const user = await prisma.user.findUnique({
      where: { email: session.user.email },
      include: {
        profile: true
      }
    });

    if (!user) {
      return NextResponse.json(
        { error: 'User not found' },
        { status: 404 }
      );
    }

    const body = await req.json();
    const { receiverId, content, attachments, projectId } = body;

    if (!receiverId || !content?.trim()) {
      return NextResponse.json(
        { error: 'Receiver ID and content are required' },
        { status: 400 }
      );
    }

    if (receiverId === user.id) {
      return NextResponse.json(
        { error: 'Cannot send message to yourself' },
        { status: 400 }
      );
    }

    // Verify receiver exists
    const receiver = await prisma.user.findUnique({
      where: { id: receiverId }
    });

    if (!receiver) {
      return NextResponse.json(
        { error: 'Receiver not found' },
        { status: 404 }
      );
    }

    // Verify project exists if projectId is provided
    if (projectId) {
      const project = await prisma.project.findUnique({
        where: { id: projectId }
      });

      if (!project) {
        return NextResponse.json(
          { error: 'Project not found' },
          { status: 404 }
        );
      }
    }

    const message = await prisma.message.create({
      data: {
        senderId: user.id,
        receiverId,
        content: content.trim(),
        attachments: attachments ? JSON.stringify(attachments) : null,
        projectId: projectId || null
      },
      include: {
        sender: {
          include: {
            profile: true
          }
        },
        receiver: {
          include: {
            profile: true
          }
        },
        project: {
          select: {
            id: true,
            title: true
          }
        }
      }
    });

    // Create notification for receiver
    await prisma.notification.create({
      data: {
        userId: receiverId,
        type: 'message_received',
        title: 'New Message',
        message: `You have received a new message from ${user.profile?.firstName || session.user.name || 'a user'}`,
        data: JSON.stringify({
          messageId: message.id,
          senderId: user.id,
          projectId: projectId || null
        })
      }
    });

    // Send WebSocket notification using the bridge
    try {
      const { wsBridge } = await import('@/lib/websocket-bridge');

      const messageData = {
        type: 'new_message',
        message: message,
      };

      // Send to receiver
      const sentToReceiver = wsBridge.sendToUser(receiverId, messageData);
      if (sentToReceiver) {
        console.log(`✅ [Message API] Sent WebSocket notification to receiver: ${receiverId}`);
      } else {
        console.log(`📵 [Message API] Receiver not connected via WebSocket: ${receiverId}`);
      }

      // Send to sender for real-time UI updates
      const sentToSender = wsBridge.sendToUser(user.id, messageData);
      if (sentToSender) {
        console.log(`✅ [Message API] Sent WebSocket confirmation to sender: ${user.id}`);
      }

      // Broadcast to the consistent conversation room
      const roomId = `conversation_${user.id < receiverId ? user.id : receiverId}_${user.id < receiverId ? receiverId : user.id}`;
      const broadcastCount = wsBridge.broadcastToRoom(roomId, messageData);
      if (broadcastCount > 0) {
        console.log(`✅ [Message API] Broadcasted WebSocket notification to room: ${roomId} (${broadcastCount} clients)`);
      }
    } catch (error) {
      console.error('❌ [Message API] Failed to import or use WebSocket bridge:', error);
    }

    return NextResponse.json({
      success: true,
      data: message,
      message: 'Message sent successfully'
    });

  } catch (error) {
    console.error('Error sending message:', error);
    return NextResponse.json(
      { 
        error: error instanceof Error ? error.message : 'Failed to send message',
        type: 'server_error'
      },
      { status: 500 }
    );
  }
}