/**
* search_posts tool handler
*/
import { ValidationError } from "../errors/index.js";
import { SearchPostsInputSchema } from "../schemas/index.js";
import { apiClient } from "../services/hn-api-client.js";
import { buildSearchParams } from "../services/search-service.js";
import type { SearchPostsInput } from "../types/index.js";
import { formatToolResponse } from "../utils/index.js";
/**
* Handle search_posts tool call
*/
export async function handleSearchPosts(args: unknown) {
// Validate input
const parseResult = SearchPostsInputSchema.safeParse(args);
if (!parseResult.success) {
throw new ValidationError("Invalid search parameters", parseResult.error.errors);
}
const input: SearchPostsInput = parseResult.data;
// Additional validation
if (input.minPoints !== undefined && input.maxPoints !== undefined) {
if (input.minPoints > input.maxPoints) {
throw new ValidationError("minPoints cannot be greater than maxPoints");
}
}
if (input.minComments !== undefined && input.maxComments !== undefined) {
if (input.minComments > input.maxComments) {
throw new ValidationError("minComments cannot be greater than maxComments");
}
}
if (input.dateAfter && input.dateBefore) {
const after = new Date(input.dateAfter);
const before = new Date(input.dateBefore);
if (after > before) {
throw new ValidationError("dateAfter cannot be later than dateBefore");
}
}
// Build API parameters
const params = buildSearchParams(input);
// Call appropriate API endpoint
const result = input.sortByDate
? await apiClient.searchByDate(params)
: await apiClient.search(params);
// Format response with pagination metadata
const response = {
results: result.hits,
pagination: {
totalResults: result.nbHits,
currentPage: result.page,
totalPages: result.nbPages,
resultsPerPage: result.hitsPerPage,
},
processingTimeMS: result.processingTimeMS,
remainingQuota: apiClient.getRemainingQuota(),
};
return formatToolResponse(response);
}