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 }
    });

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

    // Get all conversations by finding unique contacts
    const conversations = await prisma.$queryRaw`
      SELECT DISTINCT
        CASE 
          WHEN m.senderId = ${user.id} THEN m.receiverId
          ELSE m.senderId
        END as contactId,
        MAX(m.createdAt) as lastMessageTime,
        COUNT(CASE WHEN m.receiverId = ${user.id} AND m.isRead = false THEN 1 END) as unreadCount
      FROM Message m
      WHERE m.senderId = ${user.id} OR m.receiverId = ${user.id}
      GROUP BY contactId
      ORDER BY lastMessageTime DESC
    ` as Array<{
      contactId: string;
      lastMessageTime: Date;
      unreadCount: bigint;
    }>;

    // Get contact details and last message for each conversation
    const conversationData = await Promise.all(
      conversations.map(async (conv) => {
        const contact = await prisma.user.findUnique({
          where: { id: conv.contactId },
          include: {
            profile: true
          }
        });

        const lastMessage = await prisma.message.findFirst({
          where: {
            OR: [
              { senderId: user.id, receiverId: conv.contactId },
              { senderId: conv.contactId, receiverId: user.id }
            ]
          },
          orderBy: { createdAt: 'desc' },
          include: {
            project: {
              select: {
                id: true,
                title: true
              }
            }
          }
        });

        return {
          contactId: conv.contactId,
          contact,
          lastMessage,
          lastMessageTime: conv.lastMessageTime,
          unreadCount: Number(conv.unreadCount)
        };
      })
    );

    return NextResponse.json({
      success: true,
      data: conversationData.filter(conv => conv.contact) // Filter out deleted users
    });

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