import { NextRequest, NextResponse } from 'next/server'
import { verifyWebhook, handleIncomingMessage, generateAIResponse } from '@/lib/ai/whatsapp'
import { db } from '@/lib/db'

export async function GET(request: NextRequest) {
  const searchParams = request.nextUrl.searchParams
  const mode = searchParams.get('hub.mode') || ''
  const token = searchParams.get('hub.verify_token') || ''
  const challenge = searchParams.get('hub.challenge') || ''

  const result = verifyWebhook(mode, token, challenge)

  if (result) {
    return new NextResponse(result, {
      status: 200,
      headers: { 'Content-Type': 'text/plain' },
    })
  }

  return NextResponse.json({ error: 'Verification failed' }, { status: 403 })
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json()

    // Verify this is a WhatsApp webhook event
    const object = body.object
    if (object !== 'whatsapp_business_account') {
      return NextResponse.json({ error: 'Not a WhatsApp event' }, { status: 400 })
    }

    // Process the incoming message asynchronously
    // Don't await - respond immediately to webhook
    handleIncomingMessage(body).catch((err) => {
      console.error('Webhook processing error:', err instanceof Error ? err.message : err)
    })

    // Always return 200 immediately to acknowledge webhook
    return NextResponse.json({ status: 'received' }, { status: 200 })
  } catch (error) {
    console.error('WhatsApp webhook error:', error instanceof Error ? error.message : error)
    return NextResponse.json(
      { error: 'Webhook processing failed' },
      { status: 500 }
    )
  }
}

// Command handler for WhatsApp bot commands
export async function PUT(request: NextRequest) {
  try {
    const body = await request.json()
    const { phoneNumber, command } = body as {
      phoneNumber: string
      command: string
    }

    if (!phoneNumber || !command) {
      return NextResponse.json(
        { error: 'Phone number and command are required.' },
        { status: 400 }
      )
    }

    let response: string

    switch (command.toLowerCase()) {
      case '/bursaries':
        response = await generateAIResponse(
          'List the top 5 currently open bursaries for South African students with application details.'
        )
        break
      case '/careers':
        response = await generateAIResponse(
          'What are the top careers in demand in South Africa right now? Give practical advice.'
        )
        break
      case '/results':
        response = await generateAIResponse(
          'How does the South African matric results system work? Explain APS scores.'
        )
        break
      case '/help':
        response = `🤖 *Studo-Guide WhatsApp Bot*

Available commands:
*/bursaries* - List open bursaries
*/careers* - Top career advice
*/results* - Matric results info
*/help* - Show this menu

Or just type any question about careers, universities, bursaries, or studying!`
        break
      default:
        response = await generateAIResponse(command)
    }

    // Log the command
    try {
      await db.whatsAppMessage.create({
        data: {
          phoneNumber,
          direction: 'outbound',
          message: response,
          status: 'sent',
        },
      })
    } catch {
      // Non-critical
    }

    return NextResponse.json({ response })
  } catch (error) {
    console.error('WhatsApp command error:', error instanceof Error ? error.message : error)
    return NextResponse.json(
      { error: 'Failed to process command.' },
      { status: 500 }
    )
  }
}
