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

function collection() {
  return getCollection<NoteAgentActionDoc>('note_agent_actions', '/workspaceId');
}

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

  if (query.noteId) filter.noteId = query.noteId;
  if (query.state) filter.state = query.state;
  if (query.actionType) filter.actionType = query.actionType;
  if (query.correlationId) filter.correlationId = query.correlationId;
  if (query.idempotencyKey) filter.idempotencyKey = query.idempotencyKey;

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

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

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

  const merged: NoteAgentActionDoc = {
    ...existing,
    ...updates,
    id: existing.id,
    workspaceId: existing.workspaceId,
    userId: existing.userId,
    productId: existing.productId,
    noteId: existing.noteId,
    actorId: existing.actorId,
    actorType: existing.actorType,
    toolName: existing.toolName,
    actionType: existing.actionType,
  };

  return collection().upsert(merged);
}
