/**
 * Notifications repository — cloud-agnostic via @bytelyst/datastore.
 */

import { getCollection } from '../../lib/datastore.js';
import type { DeviceDoc, NotificationPrefsDoc } from './types.js';

function devicesCollection() {
  return getCollection<DeviceDoc>('devices', '/userId');
}

function prefsCollection() {
  return getCollection<NotificationPrefsDoc>('notification_prefs', '/userId');
}

// ── Devices ──

export async function getDevicesByUser(userId: string, productId: string): Promise<DeviceDoc[]> {
  return devicesCollection().findMany({
    filter: { productId, userId },
  });
}

export async function upsertDevice(doc: DeviceDoc): Promise<DeviceDoc> {
  return devicesCollection().upsert(doc);
}

export async function removeDevice(id: string, userId: string): Promise<boolean> {
  try {
    await devicesCollection().delete(id, userId);
    return true;
  } catch {
    return false;
  }
}

// ── Preferences ──

export async function getPrefs(
  userId: string,
  productId: string
): Promise<NotificationPrefsDoc | null> {
  const id = `prefs_${productId}_${userId}`;
  try {
    return await prefsCollection().findById(id, userId);
  } catch {
    return null;
  }
}

export async function upsertPrefs(doc: NotificationPrefsDoc): Promise<NotificationPrefsDoc> {
  return prefsCollection().upsert(doc);
}
