import { prismaUnscoped } from '../../lib/prisma';

/**
 * The phones each user is signed in on, for push notifications.
 *
 * A device token belongs to a user, not a tenant — it carries no tenantId —
 * so every query here is bounded by the user id taken from the verified
 * session (or, when pushing, by user ids the caller already resolved within
 * its tenant), never by anything the client sends.
 */

export type DevicePlatform = 'ANDROID' | 'IOS';

/**
 * Remember this install for [userId]. A token is one install, so if someone
 * else last signed in on this phone it moves to the new user.
 */
export async function registerDevice(userId: string, token: string, platform: DevicePlatform): Promise<void> {
  await prismaUnscoped.deviceToken.upsert({
    where: { token },
    create: { userId, token, platform },
    update: { userId, platform, lastSeenAt: new Date() },
  });
}

/** Forget this install — on sign-out. Only the caller's own token goes. */
export async function unregisterDevice(userId: string, token: string): Promise<number> {
  const { count } = await prismaUnscoped.deviceToken.deleteMany({ where: { token, userId } });
  return count;
}

/** Each user's tokens, for one push to all their phones. */
export async function tokensByUser(userIds: string[]): Promise<Map<string, string[]>> {
  const map = new Map<string, string[]>();
  if (userIds.length === 0) return map;
  const rows = await prismaUnscoped.deviceToken.findMany({
    where: { userId: { in: userIds } },
    select: { userId: true, token: true },
  });
  for (const r of rows) map.set(r.userId, [...(map.get(r.userId) ?? []), r.token]);
  return map;
}

/** Drop tokens the push service reported dead (an uninstall, a reinstall). */
export async function dropDeadTokens(tokens: string[]): Promise<void> {
  if (tokens.length === 0) return;
  await prismaUnscoped.deviceToken.deleteMany({ where: { token: { in: tokens } } });
}
