import { NextRequest, NextResponse } from 'next/server'
import { supabase } from '@/lib/supabase'
import { sendPushNotification } from '@/lib/webPush'
import type { MessageNotificationPayload } from '@/app/types/notifications'

type NotifyMessageRequest = {
  conversationId: string
  messagePreview: string
  conversationName?: string
}

// Route API pour notifier les participants d'un nouveau message (push notifications)
export async function POST(request: NextRequest) {
  try {
    const authUserCookie = request.cookies.get('AuthUser')

    if (!authUserCookie?.value) {
      return NextResponse.json({ error: 'User not authenticated' }, { status: 401 })
    }

    // Récupération de l'utilisateur (Laravel) depuis le cookie
    let sender: { id: number; name?: string }
    try {
      sender = JSON.parse(authUserCookie.value)
    } catch (error) {
      return NextResponse.json({ error: 'Invalid user session' }, { status: 401 })
    }

    const body = (await request.json()) as NotifyMessageRequest

    if (!body?.conversationId || !body?.messagePreview) {
      return NextResponse.json({ error: 'conversationId and messagePreview are required' }, { status: 400 })
    }

    // 1. Récupérer les participants de la conversation avec leur main_id (ID Laravel)
    const { data: participants, error: participantsError } = await supabase
      .from('conversation_participants')
      .select('users!inner(id, main_id, name)')
      .eq('conversation_id', body.conversationId)

    if (participantsError) {
      console.error('Error fetching conversation participants:', participantsError)
      return NextResponse.json({ error: 'Failed to fetch participants' }, { status: 500 })
    }

    const recipientMainIds = (participants || [])
      .map((p: any) => p?.users?.main_id as number | undefined)
      .filter((mainId): mainId is number => typeof mainId === 'number' && mainId !== sender.id)

    if (recipientMainIds.length === 0) {
      return NextResponse.json({ success: true, notified: 0 })
    }

    // 2. Récupérer les subscriptions push associées aux destinataires
    const { data: subscriptions, error: subscriptionsError } = await supabase
      .from('push_subscriptions')
      .select('subscription, user_id')
      .in('user_id', recipientMainIds)

    if (subscriptionsError) {
      console.error('Error fetching push subscriptions:', subscriptionsError)
      return NextResponse.json({ error: 'Failed to fetch push subscriptions' }, { status: 500 })
    }

    if (!subscriptions || subscriptions.length === 0) {
      return NextResponse.json({ success: true, notified: 0 })
    }

    // 3. Construire le payload de notification (type: message)
    const senderName = sender.name || 'Someone'
    const preview = body.messagePreview.length > 120 ? `${body.messagePreview.slice(0, 117)}...` : body.messagePreview
    const url = `/chat?conversation=${body.conversationId}`

    const payload: MessageNotificationPayload = {
      type: 'message',
      title: 'OwaSpaces',
      body: `${senderName}: ${preview}`,
      url,
      icon:'/logo.png',
      conversationId: body.conversationId,
      senderMainId: sender.id,
      senderName,
      messagePreview: preview,
      timestamp: new Date().toISOString(),
    }

    // 4. Envoyer la notification à chaque subscription (capture des erreurs individuelles)
    let notified = 0

    await Promise.all(
      subscriptions.map(async ({ subscription }) => {
        try {
          await sendPushNotification(subscription as any, payload)
          notified += 1
        } catch (error) {
          console.error('Failed to deliver push notification:', error)
        }
      })
    )

    return NextResponse.json({ success: true, notified })
  } catch (error) {
    console.error('Error notifying participants:', error)
    return NextResponse.json({ error: 'Server error while notifying participants' }, { status: 500 })
  }
}

