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

// POST /api/messages — Send a message or start a conversation
export async function POST(request: NextRequest) {
    try {
        const userId = request.headers.get('x-user-id')
        const { businessId, conversationId, content } = await request.json()

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

        if (!content) {
            return NextResponse.json({ error: 'Contenu manquant' }, { status: 400 })
        }

        let conversation;
        let receiverId;
        let finalBusinessId = businessId;

        if (conversationId) {
            // Case 1: Reply to an existing conversation
            conversation = await prisma.conversation.findUnique({
                where: { id: conversationId },
                include: { participants: true }
            });

            if (!conversation) {
                return NextResponse.json({ error: 'Conversation introuvable' }, { status: 404 });
            }

            const isParticipant = conversation.participants.some(p => p.userId === userId);
            if (!isParticipant) {
                return NextResponse.json({ error: 'Vous n\'êtes pas participant à cette conversation' }, { status: 403 });
            }

            // Find the other participant to determine receiverId
            const otherParticipant = conversation.participants.find(p => p.userId !== userId);
            receiverId = otherParticipant?.userId;
            finalBusinessId = conversation.businessId;

        } else if (businessId) {
            // Case 2: Start a new conversation via business profile
            const business = await prisma.business.findUnique({
                where: { id: businessId },
                select: { ownerId: true }
            })

            if (!business) {
                return NextResponse.json({ error: 'Entreprise introuvable' }, { status: 404 })
            }

            receiverId = business.ownerId

            if (userId === receiverId) {
                return NextResponse.json({ error: 'Vous ne pouvez pas vous envoyer un message à vous-même' }, { status: 400 })
            }

            // Find or create a conversation for this user + business
            conversation = await prisma.conversation.findFirst({
                where: {
                    businessId: businessId,
                    participants: {
                        every: {
                            userId: { in: [userId, receiverId] }
                        }
                    }
                }
            })

            if (!conversation) {
                conversation = await prisma.conversation.create({
                    data: {
                        businessId: businessId,
                        participants: {
                            create: [
                                { userId: userId },
                                { userId: receiverId }
                            ]
                        }
                    }
                })
            }
        } else {
            return NextResponse.json({ error: 'ID Business ou ID Conversation manquant' }, { status: 400 })
        }

        // 3. Create the message
        const message = await prisma.message.create({
            data: {
                content,
                senderId: userId,
                conversationId: conversation.id
            }
        })

        // 4. Update conversation updatedAt timestamp AND reset archive status for all
        await prisma.$transaction([
            prisma.conversation.update({
                where: { id: conversation.id },
                data: { updatedAt: new Date() }
            }),
            prisma.conversationParticipant.updateMany({
                where: { conversationId: conversation.id },
                data: { isArchived: false }
            })
        ])

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