import { NextResponse } from 'next/server'
import { requireAdmin } from '@/lib/auth'
import { testWebhook } from '@/lib/discord-webhook'

export async function POST(request: Request) {
  try {
    const adminCheck = await requireAdmin()
    if (adminCheck) return adminCheck

    const { webhookUrl } = await request.json()

    if (!webhookUrl) {
      return NextResponse.json(
        { error: 'Webhook URL is required' },
        { status: 400 }
      )
    }

    // Validate Discord webhook URL format
    if (!webhookUrl.startsWith('https://discord.com/api/webhooks/') &&
        !webhookUrl.startsWith('https://discordapp.com/api/webhooks/')) {
      return NextResponse.json(
        { error: 'Invalid Discord webhook URL' },
        { status: 400 }
      )
    }

    const result = await testWebhook(webhookUrl)

    if (result.success) {
      return NextResponse.json({ success: true })
    } else {
      return NextResponse.json(
        { error: result.error || 'Failed to send webhook message' },
        { status: 500 }
      )
    }
  } catch (error) {
    console.error('Webhook test failed:', error)
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    )
  }
}
