import { NotFoundError } from '../../lib/errors.js';
import { getCollection } from '../../lib/datastore.js';
import type { ListReviewsQuery, ReviewItemDoc } from './types.js';

function reviewCollection() {
  return getCollection<ReviewItemDoc>('review_queue', '/productId');
}

export async function create(doc: ReviewItemDoc): Promise<ReviewItemDoc> {
  return reviewCollection().create(doc);
}

export async function getById(id: string, productId: string): Promise<ReviewItemDoc> {
  const review = await reviewCollection().findById(id, productId);
  if (!review) throw new NotFoundError(`Review '${id}' not found`);
  return review;
}

export async function list(productId: string, query: ListReviewsQuery): Promise<ReviewItemDoc[]> {
  return reviewCollection().findMany({
    filter: {
      productId,
      ...(query.status ? { status: query.status } : {}),
      ...(query.priority ? { priority: query.priority } : {}),
      ...(query.scope ? { scope: query.scope } : {}),
      ...(query.orgId ? { orgId: query.orgId } : {}),
      ...(query.workspaceId ? { workspaceId: query.workspaceId } : {}),
      ...(query.assignedTo ? { assignedTo: query.assignedTo } : {}),
      ...(query.runId ? { runId: query.runId } : {}),
    },
    sort: { createdAt: -1 },
    limit: query.limit,
  });
}

export async function update(
  id: string,
  productId: string,
  updates: Partial<ReviewItemDoc>
): Promise<ReviewItemDoc> {
  const updated = await reviewCollection().update(id, productId, {
    ...updates,
    updatedAt: new Date().toISOString(),
  });
  if (!updated) throw new NotFoundError(`Review '${id}' not found`);
  return updated;
}

export async function listExpired(productId: string, now: string): Promise<ReviewItemDoc[]> {
  const pending = await reviewCollection().findMany({
    filter: { productId, status: 'pending' },
    sort: { createdAt: -1 },
    limit: 500,
  });
  const assigned = await reviewCollection().findMany({
    filter: { productId, status: 'assigned' },
    sort: { createdAt: -1 },
    limit: 500,
  });
  return [...pending, ...assigned].filter(r => r.dueAt && r.dueAt < now);
}

export async function listAll(productId: string, limit = 500): Promise<ReviewItemDoc[]> {
  return reviewCollection().findMany({
    filter: { productId },
    sort: { createdAt: -1 },
    limit,
  });
}
