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

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

function collection() {
  return getCollection<LicenseDoc>('licenses', '/userId');
}

export function generateKey(licensePrefix: string): string {
  const seg = () => crypto.randomBytes(2).toString('hex').toUpperCase();
  return `${licensePrefix}-${seg()}-${seg()}-${seg()}`;
}

export async function getByKey(key: string, productId: string): Promise<LicenseDoc | null> {
  return collection().findOne({
    filter: { productId, key: key.toUpperCase() },
  });
}

export async function getByUserId(userId: string, productId: string): Promise<LicenseDoc[]> {
  return collection().findMany({
    filter: { productId, userId },
    sort: { createdAt: -1 },
  });
}

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

export async function update(
  id: string,
  userId: string,
  updates: Partial<LicenseDoc>
): Promise<LicenseDoc | null> {
  try {
    return await collection().update(id, userId, {
      ...updates,
      updatedAt: new Date().toISOString(),
    });
  } catch {
    return null;
  }
}
