/**
 * WebAuthn passkey repository — CRUD for auth_passkeys container.
 */

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

function passkeysCollection() {
  return getCollection<PasskeyDoc>('auth_passkeys', '/userId');
}

export async function create(doc: PasskeyDoc): Promise<PasskeyDoc> {
  return passkeysCollection().create(doc);
}

export async function getByCredentialId(credentialId: string): Promise<PasskeyDoc | null> {
  return passkeysCollection().findOne({
    filter: { credentialId },
  });
}

export async function listByUser(userId: string): Promise<PasskeyDoc[]> {
  return passkeysCollection().findMany({
    filter: { userId },
  });
}

export async function updateCounter(
  userId: string,
  credentialId: string,
  newCounter: number
): Promise<void> {
  const id = `pk_${credentialId}`;
  try {
    await passkeysCollection().update(id, userId, {
      counter: newCounter,
      lastUsedAt: new Date().toISOString(),
    } as Partial<PasskeyDoc>);
  } catch {
    // best-effort
  }
}

export async function remove(userId: string, credentialId: string): Promise<boolean> {
  const id = `pk_${credentialId}`;
  try {
    await passkeysCollection().delete(id, userId);
    return true;
  } catch {
    return false;
  }
}
