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<{ id: string }> }
) {
  const { id } = await params;
  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 }
      );
    }

    const message = await prisma.message.findFirst({
      where: {
        id: id,
        OR: [
          { senderId: user.id },
          { receiverId: user.id }
        ]
      },
      include: {
        sender: {
          include: {
            profile: true
          }
        },
        receiver: {
          include: {
            profile: true
          }
        },
        project: {
          select: {
            id: true,
            title: true
          }
        }
      }
    });

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

    return NextResponse.json({
      success: true,
      data: message
    });

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

export async function PUT(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params;
  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 }
      );
    }

    const body = await req.json();
    const { isRead } = body;

    const message = await prisma.message.findFirst({
      where: {
        id: id,
        receiverId: user.id // Only receiver can mark as read
      }
    });

    if (!message) {
      return NextResponse.json(
        { error: 'Message not found or not authorized' },
        { status: 404 }
      );
    }

    const updatedMessage = await prisma.message.update({
      where: { id: id },
      data: {
        isRead: isRead !== undefined ? isRead : message.isRead,
        readAt: isRead ? new Date() : message.readAt
      },
      include: {
        sender: {
          include: {
            profile: true
          }
        },
        receiver: {
          include: {
            profile: true
          }
        },
        project: {
          select: {
            id: true,
            title: true
          }
        }
      }
    });

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

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

export async function DELETE(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params;
  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 }
      );
    }

    const message = await prisma.message.findFirst({
      where: {
        id: id,
        senderId: user.id // Only sender can delete
      }
    });

    if (!message) {
      return NextResponse.json(
        { error: 'Message not found or not authorized' },
        { status: 404 }
      );
    }

    await prisma.message.delete({
      where: { id: id }
    });

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

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