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

import { getCollection } from '../../lib/datastore.js';
import type { UserSettingsDoc } from './types.js';

function collection() {
  return getCollection<UserSettingsDoc>('settings', '/userId');
}

export function getSettingsId(productId: string, userId: string): string {
  return `set_${productId}_${userId}`;
}

export async function getByUserId(
  userId: string,
  productId: string
): Promise<UserSettingsDoc | null> {
  const id = getSettingsId(productId, userId);
  try {
    return await collection().findById(id, userId);
  } catch {
    return null;
  }
}

export async function upsert(doc: UserSettingsDoc): Promise<UserSettingsDoc> {
  return collection().upsert(doc);
}
