import "server-only";
import { prisma } from "@/lib/db";
import type { NotificationType } from "@prisma/client";

/**
 * Notification reads.
 *
 * Notifications are strictly personal: every query is scoped by `userId` so a
 * user can never read or count another user's rows.
 */

export interface NotificationRow {
  id: string;
  type: NotificationType;
  title: string;
  body: string;
  link: string | null;
  readAt: Date | null;
  createdAt: Date;
}

export interface NotificationFilters {
  unreadOnly?: boolean;
  /** Cap the number of rows returned; defaults to the newest 100. */
  take?: number;
}

export async function listNotifications(
  userId: string,
  filters: NotificationFilters = {}
): Promise<NotificationRow[]> {
  const notifications = await prisma.notification.findMany({
    where: {
      userId,
      ...(filters.unreadOnly ? { readAt: null } : {}),
    },
    orderBy: { createdAt: "desc" },
    take: filters.take ?? 100,
    select: {
      id: true,
      type: true,
      title: true,
      body: true,
      link: true,
      readAt: true,
      createdAt: true,
    },
  });

  return notifications;
}

export async function countUnread(userId: string): Promise<number> {
  return prisma.notification.count({ where: { userId, readAt: null } });
}

export interface NotificationTypeRollup {
  type: NotificationType;
  total: number;
  unread: number;
}

/** Per-type counts so the header can summarise the inbox at a glance. */
export async function rollupNotificationsByType(
  userId: string
): Promise<NotificationTypeRollup[]> {
  const [totals, unread] = await Promise.all([
    prisma.notification.groupBy({
      by: ["type"],
      where: { userId },
      _count: { _all: true },
    }),
    prisma.notification.groupBy({
      by: ["type"],
      where: { userId, readAt: null },
      _count: { _all: true },
    }),
  ]);

  const unreadByType: Record<string, number> = {};
  for (const row of unread) {
    unreadByType[row.type] = row._count._all;
  }

  return totals
    .map((row) => ({
      type: row.type,
      total: row._count._all,
      unread: unreadByType[row.type] ?? 0,
    }))
    .sort((a, b) => b.total - a.total);
}
