import { getCollection } from '../../lib/datastore.js';
import type { WorkspaceDoc, ListWorkspacesQuery } from './types.js';

function collection() {
  return getCollection<WorkspaceDoc>('workspaces', '/userId');
}

export async function listWorkspaces(
  userId: string,
  productId: string,
  query: ListWorkspacesQuery
): Promise<{ items: WorkspaceDoc[]; total: number }> {
  const filter = { userId, productId };
  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 getWorkspace(id: string, userId: string): Promise<WorkspaceDoc | null> {
  return collection().findById(id, userId);
}

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

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

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

  return collection().upsert(merged);
}
