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

function collection() {
  return getCollection<NoteTaskDoc>('note_tasks', '/workspaceId');
}

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

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

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

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

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

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

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

  return collection().upsert(merged);
}
