import * as admin from 'firebase-admin'
import { db } from '../config/firebase'
import { sendPartnerAnsweredNotification } from '../services/fcm'
import { CoupleDoc, UserDoc } from '../types'

export function startAnswerListener(): () => void {
  console.log('[listener] watching answer writes...')

  // Watch every answer document across all couples and threads
  const unsubscribe = db()
    .collectionGroup('answers')
    .onSnapshot(
      async (snapshot) => {
        const creates = snapshot.docChanges().filter((c) => c.type === 'added')

        for (const change of creates) {
          const answerRef = change.doc.ref
          // Path: couples/{coupleId}/question_threads/{threadId}/answers/{userId}
          const threadRef = answerRef.parent.parent
          const coupleRef = threadRef?.parent.parent

          if (!coupleRef || !threadRef) continue

          const answererId = answerRef.id
          const coupleId = coupleRef.id

          try {
            const coupleSnap = await coupleRef.get()
            if (!coupleSnap.exists) continue

            const couple = coupleSnap.data() as CoupleDoc
            const partnerId = couple.userIds.find((id) => id !== answererId)
            if (!partnerId) continue

            // Only notify if partner has NOT already answered this thread
            const partnerAnswerSnap = await threadRef
              .collection('answers')
              .doc(partnerId)
              .get()
            if (partnerAnswerSnap.exists) continue

            const [partnerSnap, answererSnap] = await Promise.all([
              db().collection('users').doc(partnerId).get(),
              db().collection('users').doc(answererId).get(),
            ])

            const partner = partnerSnap.data() as UserDoc | undefined
            const answerer = answererSnap.data() as UserDoc | undefined

            if (!partner?.fcmToken) continue

            // Use a generic placeholder — we don't include partner names in push text
            const answererName = answerer?.displayName ?? 'Someone'
            await sendPartnerAnsweredNotification(partner.fcmToken, answererName)
            console.log(`[listener] notified ${partnerId} that ${answererId} answered in couple ${coupleId}`)
          } catch (err) {
            console.error(`[listener] error processing answer ${answerRef.path}:`, err)
          }
        }
      },
      (err) => {
        console.error('[listener] answer snapshot error:', err)
      }
    )

  return unsubscribe
}
