import type {
  DocumentSearchFilters,
  DocumentSearchRequest,
  DocumentSearchTimeRange,
} from "@/types/search";

interface BuildSearchRequestArgs {
  workspaceId: string | null;
  activeDocumentId: string | null;
  query: string;
  filters: Omit<DocumentSearchFilters, "timeRange">;
  timeRange: DocumentSearchTimeRange;
}

export function buildSearchRequest({
  workspaceId,
  activeDocumentId,
  query,
  filters,
  timeRange,
}: BuildSearchRequestArgs): DocumentSearchRequest | null {
  if (!workspaceId) {
    return null;
  }

  const normalizedFilters: DocumentSearchFilters = {
    ...filters,
    timeRange,
    onlyCurrentPage: filters.onlyCurrentPage && Boolean(activeDocumentId),
  };

  return {
    workspaceId,
    documentId: normalizedFilters.onlyCurrentPage ? activeDocumentId ?? undefined : undefined,
    query,
    filters: normalizedFilters,
  };
}
