import { getCollection } from '../../lib/datastore.js';
import { NotFoundError } from '../../lib/errors.js';
import type { IncidentDoc } from './types.js';

function collection() {
  return getCollection<IncidentDoc>('incidents', '/productId');
}

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

export async function listActiveIncidents(productId: string): Promise<IncidentDoc[]> {
  return collection().findMany({
    filter: { productId, status: { $ne: 'resolved' } },
    sort: { createdAt: -1 },
  });
}

export async function getIncident(id: string, productId: string): Promise<IncidentDoc> {
  const doc = await collection().findById(id, productId);
  if (!doc) throw new NotFoundError(`Incident '${id}' not found`);
  return doc;
}

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

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