/**
 * Products repository — cloud-agnostic via @bytelyst/datastore.
 * Products are the central registry; productId is the partition key.
 */

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

function collection() {
  return getCollection<ProductDoc>('products', '/productId');
}

export async function getAll(): Promise<ProductDoc[]> {
  return collection().findMany({
    sort: { displayName: 1 },
  });
}

export async function getById(productId: string): Promise<ProductDoc | null> {
  try {
    return await collection().findById(productId, productId);
  } catch {
    return null;
  }
}

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

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