// WhatsApp Gateway Integration
// Handles sending and receiving WhatsApp messages via webhook

import { db } from '@/lib/db'
import { chatCompletion } from './ollama'

interface WhatsAppConfig {
  apiKey: string
  apiBaseUrl: string
  phoneNumberId: string
  verifyToken: string
}

/**
 * Get WhatsApp configuration from environment variables
 */
function getConfig(): WhatsAppConfig {
  const apiKey = process.env.WHATSAPP_API_KEY || ''
  const apiBaseUrl = process.env.WHATSAPP_API_BASE_URL || ''
  const phoneNumberId = process.env.WHATSAPP_PHONE_NUMBER_ID || ''
  const verifyToken = process.env.WHATSAPP_VERIFY_TOKEN || ''

  return { apiKey, apiBaseUrl, phoneNumberId, verifyToken }
}

/**
 * Check if WhatsApp integration is configured
 */
export function isConfigured(): boolean {
  const config = getConfig()
  return !!(config.apiKey && config.apiBaseUrl && config.phoneNumberId)
}

/**
 * Send a WhatsApp message to a phone number
 */
export async function sendMessage(phoneNumber: string, message: string): Promise<boolean> {
  const config = getConfig()

  if (!isConfigured()) {
    console.warn('WhatsApp not configured. Would send:', { phoneNumber, message })
    // Log the message for development purposes
    await logMessage(null, phoneNumber, 'outbound', message, 'logged')
    return false
  }

  try {
    const response = await fetch(
      `${config.apiBaseUrl}/v18.0/${config.phoneNumberId}/messages`,
      {
        method: 'POST',
        headers: {
          Authorization: `Bearer ${config.apiKey}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          messaging_product: 'whatsapp',
          to: phoneNumber,
          type: 'text',
          text: { body: message },
        }),
      }
    )

    if (!response.ok) {
      throw new Error(`WhatsApp API error: ${response.status}`)
    }

    const data = await response.json()
    await logMessage(null, phoneNumber, 'outbound', message, 'sent', data.messages?.[0]?.id)
    return true
  } catch (error) {
    console.error('Failed to send WhatsApp message:', error instanceof Error ? error.message : error)
    await logMessage(null, phoneNumber, 'outbound', message, 'failed')
    return false
  }
}

/**
 * Send a template WhatsApp message
 */
export async function sendTemplateMessage(
  phoneNumber: string,
  template: string,
  params: Record<string, string> = {}
): Promise<boolean> {
  const config = getConfig()

  if (!isConfigured()) {
    console.warn('WhatsApp not configured. Would send template:', { phoneNumber, template, params })
    return false
  }

  try {
    const components = Object.entries(params).map(([key, value]) => ({
      type: 'body' as const,
      parameters: [{ type: 'text' as const, text: value }],
    }))

    const response = await fetch(
      `${config.apiBaseUrl}/v18.0/${config.phoneNumberId}/messages`,
      {
        method: 'POST',
        headers: {
          Authorization: `Bearer ${config.apiKey}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          messaging_product: 'whatsapp',
          to: phoneNumber,
          type: 'template',
          template: {
            name: template,
            language: { code: 'en' },
            components,
          },
        }),
      }
    )

    if (!response.ok) {
      throw new Error(`WhatsApp template error: ${response.status}`)
    }

    return true
  } catch (error) {
    console.error('Failed to send template message:', error instanceof Error ? error.message : error)
    return false
  }
}

/**
 * Handle incoming WhatsApp webhook message
 */
export async function handleIncomingMessage(body: Record<string, unknown>): Promise<void> {
  try {
    const entry = body.entry as Array<Record<string, unknown>>[]
    if (!entry || entry.length === 0) return

    const changes = entry[0]?.changes as Array<Record<string, unknown>>[]
    if (!changes || changes.length === 0) return

    const value = changes[0]?.value as Record<string, unknown>
    const messages = value?.messages as Array<Record<string, unknown>>

    if (!messages || messages.length === 0) return

    for (const msg of messages) {
      const from = msg.from as string
      const text = (msg.text as Record<string, unknown>)?.body as string
      const messageId = msg.id as string

      if (!text) continue

      // Log incoming message
      await logMessage(null, from, 'inbound', text, 'received', messageId)

      // Look up user by phone
      const user = await db.user.findFirst({
        where: { phone: from },
      })

      // Generate AI response
      const response = await generateAIResponse(text, {
        userId: user?.id,
        grade: user?.grade,
        province: user?.province,
      })

      // Send the response
      await sendMessage(from, response)
    }
  } catch (error) {
    console.error('Error processing incoming WhatsApp message:', error)
  }
}

/**
 * Verify WhatsApp webhook
 */
export function verifyWebhook(
  mode: string,
  token: string,
  challenge: string
): string | null {
  const config = getConfig()

  if (mode === 'subscribe' && token === config.verifyToken) {
    return challenge
  }

  return null
}

/**
 * Generate an AI response for a WhatsApp message
 */
export async function generateAIResponse(
  message: string,
  context?: {
    userId?: string
    grade?: number | null
    province?: string | null
  }
): Promise<string> {
  try {
    const systemPrompt = `You are Studo Guide, an AI career and education assistant for South African students. 
You help students with:
- Career guidance and advice
- Subject choices for Grade 10-12
- University and bursary information
- Study tips and motivation
- Information about South African education system

Keep your responses concise and friendly. Use South African context and examples where relevant.
${context?.grade ? `The student is in Grade ${context.grade}.` : ''}
${context?.province ? `The student is in ${context.province}.` : ''}
Keep responses under 1600 characters for WhatsApp.`

    const response = await chatCompletion([
      { role: 'system', content: systemPrompt },
      { role: 'user', content: message },
    ])

    return response
  } catch (error) {
    console.error('Failed to generate AI response:', error instanceof Error ? error.message : error)
    return "Sorry, I'm having trouble connecting to my brain right now. Please try again in a moment! 🧠"
  }
}

/**
 * Log a WhatsApp message to the database
 */
async function logMessage(
  userId: string | null,
  phoneNumber: string,
  direction: 'inbound' | 'outbound',
  message: string,
  status: string,
  externalId?: string
) {
  try {
    await db.whatsAppMessage.create({
      data: {
        userId,
        phoneNumber,
        direction,
        message,
        status,
        externalId,
      },
    })
  } catch (error) {
    console.error('Failed to log WhatsApp message:', error)
  }
}
