/**
 * Magic link repository — CRUD for magic_link_tokens container.
 */

import { getCollection } from '../../../lib/datastore.js';
import { createHash, randomBytes } from 'node:crypto';
import type { MagicLinkTokenDoc } from './types.js';

function tokensCollection() {
  return getCollection<MagicLinkTokenDoc>('magic_link_tokens', '/productId');
}

export function generateToken(): string {
  return randomBytes(32).toString('base64url');
}

export function hashToken(token: string): string {
  return createHash('sha256').update(token).digest('hex');
}

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

export async function findByHash(
  tokenHash: string,
  productId: string
): Promise<MagicLinkTokenDoc | null> {
  return tokensCollection().findOne({
    filter: { tokenHash, productId },
  });
}

export async function markUsed(id: string, productId: string): Promise<void> {
  await tokensCollection().update(id, productId, {
    usedAt: new Date().toISOString(),
  } as Partial<MagicLinkTokenDoc>);
}
