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

interface SendMessageRequest {
  receiverId: string;
  content: string;
  messageType: 'text' | 'file';
  fileUrl?: string;
  fileName?: string;
  projectId?: string;
}

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: SendMessageRequest = await req.json();
    const { receiverId, content, messageType = 'text', fileUrl, fileName, projectId } = body;

    // Validate required fields
    if (!receiverId) {
      return NextResponse.json(
        { error: 'Receiver ID is required' },
        { status: 400 }
      );
    }

    if (messageType === 'text' && (!content || content.trim().length === 0)) {
      return NextResponse.json(
        { error: 'Message content is required' },
        { status: 400 }
      );
    }

    if (messageType === 'file' && (!fileUrl || !fileName)) {
      return NextResponse.json(
        { error: 'File URL and filename are required for file messages' },
        { 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 }
      );
    }

    // Prepare attachments for file messages
    let attachments = null;
    if (messageType === 'file' && fileUrl && fileName) {
      attachments = JSON.stringify([{
        url: fileUrl,
        name: fileName,
        type: 'file'
      }]);
    }

    const message = await prisma.message.create({
      data: {
        senderId: user.id,
        receiverId,
        content: content?.trim() || (messageType === 'file' ? `Sent a file: ${fileName}` : ''),
        attachments,
        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
        })
      }
    });

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

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

    // TODO: Implement file upload functionality
    // This could involve uploading to a cloud storage service like AWS S3, 
    // Google Cloud Storage, or a local file storage system
    
    return NextResponse.json({
      success: false,
      error: 'File upload functionality not yet implemented'
    }, { status: 501 });

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