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

function collection() {
  return getCollection<ExportJobDoc>('export_jobs', '/productId');
}

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

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

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

export async function listExportJobs(productId: string, limit = 20): Promise<ExportJobDoc[]> {
  return collection().findMany({
    filter: { productId },
    sort: { createdAt: -1 },
    limit,
  });
}
