import { getCollection } from '../../lib/datastore.js';
import type { NoteRelationshipDoc, ListNoteRelationshipsQuery } from './types.js';
import type { FilterMap } from '@bytelyst/datastore';

function collection() {
  return getCollection<NoteRelationshipDoc>('note_relationships', '/workspaceId');
}

export async function listRelationships(
  userId: string,
  productId: string,
  query: ListNoteRelationshipsQuery
): Promise<{ items: NoteRelationshipDoc[]; total: number }> {
  const filter: FilterMap = { userId, productId, workspaceId: query.workspaceId };

  if (query.noteId) {
    filter.$or = [{ fromNoteId: query.noteId }, { toNoteId: query.noteId }];
  }

  if (query.relationshipType) {
    filter.relationshipType = query.relationshipType;
  }

  const total = await collection().count(filter);
  const items = await collection().findMany({
    filter,
    sort: { updatedAt: -1 },
    offset: query.offset,
    limit: query.limit,
  });

  return { items, total };
}

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