import { Prisma } from '@prisma/client';
import { db, prismaUnscoped } from '../../lib/prisma';
import { tenantHasFeature } from '../../middleware/requireFeature';

/**
 * The in-app inbox (Sprint 0, TEPL): everything the product pushed to a
 * person, kept so they can read it again on the web portal — where there is
 * no phone notification to fall back on. Written next to every push, whether
 * or not the person has a phone registered, and only for tenants with the
 * `inbox` module on.
 */

/** Record one alert for each user. Called from pushTo, outside any request, so it is unscoped and stamps the tenant itself. */
export async function recordInbox(
  tenantId: string,
  kind: string,
  refId: string,
  userIds: string[],
  message: { title: string; body: string; data?: Record<string, string> },
): Promise<void> {
  if (userIds.length === 0 || !(await tenantHasFeature(tenantId, 'inbox'))) return;
  await prismaUnscoped.inboxItem.createMany({
    data: [...new Set(userIds)].map((userId) => ({
      tenantId,
      userId,
      kind,
      refId,
      title: message.title.slice(0, 200),
      body: message.body.slice(0, 1000),
      data: message.data ? (message.data as Prisma.InputJsonValue) : undefined,
    })),
    skipDuplicates: true,
  });
}

const PAGE = 30;

/** The caller's own inbox, newest first; `before` (an item id) pages back. */
export async function listInbox(userId: string, opts: { unreadOnly?: boolean; before?: string }) {
  let cursorDate: Date | undefined;
  if (opts.before) {
    const cursor = await db.inboxItem.findFirst({ where: { id: opts.before, userId }, select: { createdAt: true } });
    cursorDate = cursor?.createdAt;
  }
  const items = await db.inboxItem.findMany({
    where: { userId, ...(opts.unreadOnly ? { readAt: null } : {}), ...(cursorDate ? { createdAt: { lt: cursorDate } } : {}) },
    orderBy: { createdAt: 'desc' },
    take: PAGE + 1,
    select: { id: true, kind: true, refId: true, title: true, body: true, data: true, readAt: true, createdAt: true },
  });
  return { items: items.slice(0, PAGE), hasMore: items.length > PAGE, unread: await unreadCount(userId) };
}

export function unreadCount(userId: string) {
  return db.inboxItem.count({ where: { userId, readAt: null } });
}

/** Mark some (or all) of the caller's own items read. Others' ids simply match nothing. */
export async function markRead(userId: string, input: { ids?: string[]; all?: boolean }) {
  await db.inboxItem.updateMany({
    where: { userId, readAt: null, ...(input.all ? {} : { id: { in: input.ids ?? [] } }) },
    data: { readAt: new Date() },
  });
  return { unread: await unreadCount(userId) };
}
