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

function collection() {
  return getCollection<NoteArtifactDoc>('note_artifacts', '/workspaceId');
}

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

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

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

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

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

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

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

  return collection().upsert(merged);
}
