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,
  { params }: { params: Promise<{ projectId: string }> }
) {
  try {
    if (!prisma) {
      return NextResponse.json(
        { error: 'Database connection not available' },
        { status: 503 }
      );
    }

    const session = await getServerSession(authOptions);
    
    if (!session?.user?.email) {
      return NextResponse.json(
        { error: 'Unauthorized' },
        { status: 401 }
      );
    }

    const { projectId } = await params;
    const { searchParams } = new URL(req.url);
    const bidId = searchParams.get('bidId');

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

    try {
      // Verify user has access to this project
      const project = await prisma.project.findFirst({
        where: {
          OR: [
            { id: projectId, clientId: session.user.email },
            { 
              id: projectId, 
              bids: {
                some: {
                  freelancerId: session.user.email
                }
              }
            }
          ]
        },
        include: {
          selectedBid: true,
          client: {
            select: {
              id: true,
              email: true,
              image: true,
              profile: {
                select: {
                  firstName: true,
                  lastName: true
                }
              }
            }
          },
          bids: {
            where: {
              freelancerId: session.user.email
            },
            select: {
              id: true,
              status: true,
              freelancerId: true
            }
          }
        }
      });

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

      // Determine which bid to show messages for
      let targetBidId = bidId;
      
      if (!targetBidId) {
        // If no bidId specified, try to determine it based on user role and project status
        if (session.user.email === project.clientId) {
          // Client can see messages from selected bid if project is awarded
          targetBidId = project.selectedBidId;
        } else {
          // Freelancer can only see their own bid messages
          const userBid = project.bids.find(bid => bid.freelancerId === session.user.email);
          targetBidId = userBid?.id || null;
        }
      }

      if (!targetBidId) {
        return NextResponse.json({
          success: true,
          data: []
        });
      }

      // Get actual messages for this specific bid
      const messages = await prisma.message.findMany({
        where: {
          projectId: projectId,
          bidId: targetBidId,
          isDisabled: false // Only show enabled messages
        },
        include: {
          sender: {
            select: {
              id: true,
              email: true,
              image: true,
              profile: {
                select: {
                  firstName: true,
                  lastName: true
                }
              }
            }
          },
          bid: {
            select: {
              id: true,
              status: true
            }
          }
        },
        orderBy: {
          createdAt: 'asc'
        }
      });

      // Check if user can send new messages (chat is not disabled)
      const canSendMessage = !project.selectedBid || 
        (project.selectedBidId === targetBidId) || 
        (session.user.email === project.clientId && project.selectedBidId === targetBidId);

      // Format messages
      const formattedMessages = messages.map(message => {
        const senderName = `${message.sender.profile?.firstName || ''} ${message.sender.profile?.lastName || ''}`.trim() || 'Unknown User';
        const senderRole = message.senderId === session.user?.email ? 'client' : 'freelancer';
        
        return {
          id: message.id,
          projectId: message.projectId,
          senderId: message.senderId,
          senderName: senderName,
          senderAvatar: message.sender.image || '/assets/image/default-avatar.png',
          senderRole: senderRole,
          content: message.content,
          messageType: message.messageType,
          fileUrl: undefined,
          fileName: undefined,
          timestamp: new Date(message.createdAt).toLocaleTimeString('en-US', { 
            hour: '2-digit', 
            minute: '2-digit' 
          }),
          isRead: message.isRead,
          milestoneId: undefined
        };
      });


      // Mark messages as read
      await prisma.message.updateMany({
        where: {
          projectId: projectId,
          bidId: targetBidId,
          senderId: { not: session.user.email },
          isRead: false
        },
        data: {
          isRead: true,
          readAt: new Date()
        }
      });

      return NextResponse.json({
        success: true,
        data: {
          messages: formattedMessages,
          canSendMessage: canSendMessage,
          bidId: targetBidId,
          projectStatus: project.status
        }
      });

    } catch (dbError: any) {
      console.error('Database query error:', dbError);
      
      return NextResponse.json(
        { 
          error: 'Database operation failed',
          message: 'Unable to fetch messages due to a database error. Please try again later.',
          details: process.env.NODE_ENV === 'development' ? dbError.message : undefined
        },
        { status: 500 }
      );
    }

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