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

// POST /api/messages/[id]/report — Report a message for moderation
export async function POST(
    request: NextRequest,
    { params }: { params: Promise<{ id: string }> }
) {
    try {
        const userId = request.headers.get('x-user-id')
        const { id } = await params
        const { reason } = await request.json()

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

        // Verify message exists
        const message = await prisma.message.findUnique({
            where: { id }
        })

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

        // Check if user already reported this message
        const existingReport = await prisma.messageReport.findFirst({
            where: {
                messageId: id,
                reporterId: userId
            }
        })

        if (existingReport) {
            return NextResponse.json({ error: 'Vous avez déjà signalé ce message' }, { status: 400 })
        }

        const report = await prisma.messageReport.create({
            data: {
                messageId: id,
                reporterId: userId,
                reason: reason || 'Non spécifié'
            }
        })

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