import { db } from "@/lib/db"

export type CreateNotificationInput = {
  title: string
  body: string
  type: "broadcast" | "targeted"
  recipientUserIds?: string[]
}

export async function createNotification(
  createdById: string,
  data: CreateNotificationInput
) {
  let recipientIds = data.recipientUserIds ?? []

  if (data.type === "broadcast") {
    const users = await db.user.findMany({ select: { id: true } })
    recipientIds = users.map((u) => u.id)
  }

  return db.notification.create({
    data: {
      title: data.title,
      body: data.body,
      type: data.type,
      createdById,
      recipients: {
        create: recipientIds.map((userId) => ({ userId })),
      },
    },
  })
}

export async function getNotificationsForUser(userId: string) {
  const receipts = await db.notificationRecipient.findMany({
    where: { userId },
    orderBy: { createdAt: "desc" },
    take: 50,
    include: {
      notification: {
        include: { createdBy: { select: { name: true } } },
      },
    },
  })

  return receipts.map((r) => ({
    id: r.id,
    notificationId: r.notificationId,
    title: r.notification.title,
    body: r.notification.body,
    type: r.notification.type,
    createdBy: r.notification.createdBy.name,
    createdAt: r.notification.createdAt.toISOString(),
    readAt: r.readAt?.toISOString() ?? null,
  }))
}

export async function markAsRead(userId: string, notificationId: string) {
  return db.notificationRecipient.update({
    where: { notificationId_userId: { notificationId, userId } },
    data: { readAt: new Date() },
  })
}

// features/notifications/service.ts
export async function markAllAsRead(userId: string) {
  const unreadReceipts = await db.notificationRecipient.findMany({
    where: { userId },
    select: { id: true, readAt: true },
  })

  const unreadIds = unreadReceipts
    .filter((r) => !r.readAt)
    .map((r) => r.id)

  if (unreadIds.length === 0) return { count: 0 }

  return db.notificationRecipient.updateMany({
    where: { id: { in: unreadIds } },
    data: { readAt: new Date() },
  })
}

export async function getUnreadCount(userId: string) {
  return db.notificationRecipient.count({
    where: {
      userId,
      readAt: { equals: null },
    },
  })
}