import { NextResponse } from 'next/server'
import { prisma } from '@/lib/db'
import { sendDiscordLog } from '@/lib/discord-webhook'

export async function POST(request: Request) {
  try {
    const { apiKey, discordId, playerName, message, serverId } = await request.json()

    if (!discordId || !message) {
      return NextResponse.json({ error: 'Missing required fields' }, { status: 400 })
    }

    // Find player profile
    const profile = await prisma.playerProfile.findFirst({
      where: { discordId }
    })

    // Create report
    const report = await prisma.report.create({
      data: {
        title: `In-Game Report from ${playerName || 'Unknown'}`,
        description: message,
        status: 'OPEN',
        priority: 'MEDIUM',
        reporterId: profile?.userId || null
      }
    })

    // Send to Discord webhook if configured
    const settings = await prisma.panelSettings.findFirst()
    if (settings?.discordWebhook) {
      await sendDiscordLog(
        'admin',
        'New In-Game Report',
        message,
        [
          { name: 'Reporter', value: playerName || 'Unknown', inline: true },
          { name: 'Server', value: serverId || 'Unknown', inline: true },
          { name: 'Report ID', value: report.id.slice(0, 8), inline: true }
        ],
        settings.discordWebhook
      )
    }

    return NextResponse.json({ success: true, reportId: report.id })
  } catch (error) {
    console.error('Report submission error:', error)
    return NextResponse.json({ error: 'Failed to submit report' }, { status: 500 })
  }
}
