import { NextRequest, NextResponse } from 'next/server'
import prisma from '../../../../lib/prisma'

// GET /api/conversations/[id] — Get messages for a conversation
export async function GET(
    request: NextRequest,
    { params }: { params: Promise<{ id: string }> }
) {
    try {
        const userId = request.headers.get('x-user-id')
        const { id } = await params

        if (!userId) {
            return NextResponse.json({ error: 'Utilisateur non identifié' }, { status: 401 })
        }

        // Verify user is a participant
        const isParticipant = await prisma.conversationParticipant.findUnique({
            where: {
                userId_conversationId: {
                    userId: userId,
                    conversationId: id
                }
            }
        })

        if (!isParticipant) {
            return NextResponse.json({ error: 'Accès non autorisé' }, { status: 403 })
        }

        const messages = await prisma.message.findMany({
            where: { conversationId: id },
            orderBy: { createdAt: 'asc' },
            include: {
                sender: {
                    select: {
                        id: true,
                        name: true,
                        avatar: true
                    }
                }
            }
        })

        // Mark messages as read (where sender is not the current user)
        await prisma.message.updateMany({
            where: {
                conversationId: id,
                senderId: { not: userId },
                read: false
            },
            data: { read: true }
        })

        return NextResponse.json(messages)
    } catch (error) {
        console.error('GET /api/conversations/[id] error:', error)
        return NextResponse.json({ error: 'Erreur serveur' }, { status: 500 })
    }
}
