import { prisma } from "./db";
import { Prisma } from "@/generated/prisma/client";

type CreateNotificationInput = {
  type: string;
  title: string;
  message: string;
  cardId?: string;
  actionUrl?: string;
  meta?: Prisma.InputJsonValue;
  userId?: string;
};

export async function createNotification(input: CreateNotificationInput) {
  try {
    return await prisma.notification.create({
      data: {
        type: input.type,
        title: input.title,
        message: input.message,
        cardId: input.cardId,
        actionUrl: input.actionUrl,
        meta: input.meta,
        userId: input.userId,
      },
    });
  } catch (err) {
    console.error("[notifications] Failed to create:", err);
    return null;
  }
}

export async function getNotifications({
  userId,
  unreadOnly = false,
  limit = 50,
}: { userId: string; unreadOnly?: boolean; limit?: number }) {
  const where: Record<string, unknown> = { dismissed: false, userId };
  if (unreadOnly) where.read = false;

  return prisma.notification.findMany({
    where,
    orderBy: { createdAt: "desc" },
    take: limit,
  });
}

export async function getUnreadCount(userId: string) {
  return prisma.notification.count({
    where: { read: false, dismissed: false, userId },
  });
}

export async function markRead(id: string, userId: string) {
  return prisma.notification.update({
    where: { id, userId },
    data: { read: true },
  });
}

export async function markAllRead(userId: string) {
  return prisma.notification.updateMany({
    where: { read: false, dismissed: false, userId },
    data: { read: true },
  });
}

export async function dismissNotification(id: string, userId: string) {
  return prisma.notification.update({
    where: { id, userId },
    data: { dismissed: true },
  });
}
