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

// GET /api/conversations — List all conversations for the user
export async function GET(request: NextRequest) {
    try {
        const userId = request.headers.get('x-user-id')

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

        const { searchParams } = new URL(request.url)
        const businessId = searchParams.get('businessId')

        const conversations = await prisma.conversation.findMany({
            where: {
                participants: {
                    some: { userId: userId }
                },
                ...(businessId ? { businessId: businessId } : {})
            },
            include: {
                business: {
                    select: {
                        id: true,
                        name: true,
                        logoUrl: true,
                        slug: true,
                        ownerId: true
                    }
                },
                participants: {
                    include: {
                        user: {
                            select: {
                                id: true,
                                name: true,
                                avatar: true,
                                role: true
                            }
                        }
                    }
                },
                messages: {
                    orderBy: { createdAt: 'desc' },
                    take: 1
                }
            },
            orderBy: {
                updatedAt: 'desc'
            }
        })

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