import * as functions from 'firebase-functions'
import * as admin from 'firebase-admin'

type ReminderType = 'daily_question' | 'partner_answered' | 'streak'

interface NotificationPayload {
  userId: string
  type: ReminderType
  title?: string
  body?: string
}

/**
 * Callable function that queues a daily-question reminder.
 *
 * Expected body: { userId: string }
 * Auth context supplies the caller uid; the request `userId` must match
 * the caller to prevent cross-user notification spam.
 *
 * This is a placeholder scheduler. The actual daily scheduling will be
 * handled by a Firestore trigger / Cloud Scheduler integration later.
 */
export const sendDailyQuestionReminder = functions.https.onCall(async (data: NotificationPayload, context) => {
  const callerId = context.auth?.uid
  if (!callerId) {
    throw new functions.https.HttpsError('unauthenticated', 'Caller must be authenticated.')
  }

  const userId = data.userId
  if (!userId || typeof userId !== 'string') {
    throw new functions.https.HttpsError('invalid-argument', 'userId is required.')
  }

  // Users may only request reminders for themselves.
  if (userId !== callerId) {
    throw new functions.https.HttpsError('permission-denied', 'Cannot send notifications to another user.')
  }

  await writeNotificationRecord(userId, 'daily_question', {
    title: data.title ?? 'Your daily question is waiting!',
    body: data.body ?? "Tap to answer today's question together.",
  })

  return { queued: true, type: 'daily_question' }
})

/**
 * Callable function that queues a partner-answered notification.
 *
 * Expected body: { userId: string }
 * Auth context must match the request `userId`.
 */
export const sendPartnerAnsweredNotification = functions.https.onCall(async (data: NotificationPayload, context) => {
  const callerId = context.auth?.uid
  if (!callerId) {
    throw new functions.https.HttpsError('unauthenticated', 'Caller must be authenticated.')
  }

  const userId = data.userId
  if (!userId || typeof userId !== 'string') {
    throw new functions.https.HttpsError('invalid-argument', 'userId is required.')
  }

  if (userId !== callerId) {
    throw new functions.https.HttpsError('permission-denied', 'Cannot send notifications to another user.')
  }

  await writeNotificationRecord(userId, 'partner_answered', {
    title: data.title ?? 'Your partner just answered!',
    body: data.body ?? 'See what your partner shared.',
  })

  return { queued: true, type: 'partner_answered' }
})

async function writeNotificationRecord(
  userId: string,
  type: ReminderType,
  message: { title: string; body: string }
): Promise<void> {
  const db = admin.firestore()

  await db
    .collection('users')
    .doc(userId)
    .collection('notification_queue')
    .add({
      type,
      ...message,
      read: false,
      sent: false,
      createdAt: admin.firestore.FieldValue.serverTimestamp(),
    })
}
