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

function collection() {
  return getCollection<NoteDoc>('notes', '/workspaceId');
}

export async function listNotes(
  userId: string,
  productId: string,
  query: ListNotesQuery
): Promise<{ items: NoteDoc[]; total: number }> {
  const filter: FilterMap = { userId, productId };

  if (query.workspaceId) filter.workspaceId = query.workspaceId;
  if (query.status) filter.status = query.status;
  if (query.tag) filter.tags = { $contains: query.tag };
  if (query.search) filter.$or = [{ title: { $contains: query.search } }, { body: { $contains: query.search } }];

  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 getNote(id: string, workspaceId: string): Promise<NoteDoc | null> {
  return collection().findById(id, workspaceId);
}

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

export async function updateNote(
  id: string,
  workspaceId: string,
  updates: Partial<NoteDoc>
): Promise<NoteDoc | null> {
  const existing = await collection().findById(id, workspaceId);
  if (!existing) {
    return null;
  }

  const merged: NoteDoc = {
    ...existing,
    ...updates,
    id: existing.id,
    workspaceId: existing.workspaceId,
    userId: existing.userId,
    productId: existing.productId,
  };

  return collection().upsert(merged);
}
