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

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

function collection() {
  return getCollection<VoteDoc>('tracker_votes', '/id');
}

export async function getByItemAndUser(itemId: string, userId: string): Promise<VoteDoc | null> {
  return collection().findOne({
    filter: { itemId, userId },
  });
}

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

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

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

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