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

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

function collection() {
  return getCollection<CommentDoc>('tracker_comments', '/id');
}

export async function listByItem(itemId: string): Promise<CommentDoc[]> {
  return collection().findMany({
    filter: { itemId },
    sort: { createdAt: 1 },
  });
}

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

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

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

export async function remove(id: string): Promise<boolean> {
  try {
    await collection().delete(id, id);
    return true;
  } catch {
    return false;
  }
}

export async function countByItem(itemId: string): Promise<number> {
  return collection().count({ itemId });
}
