import { Request } from 'express';

export function parsePagination(req: Request, defaultLimit = 10) {
  const page = Math.max(parseInt(String(req.query.page || '1'), 10), 1);
  const limit = Math.min(parseInt(String(req.query.limit || String(defaultLimit)), 10), 100);
  const skip = (page - 1) * limit;
  return { page, limit, skip };
}

export function paginationMeta(page: number, limit: number, total: number) {
  return { page, limit, total, pages: Math.max(Math.ceil(total / limit), 1) };
}

export function escapeRegex(value: string) {
  return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

export function buildTextSearch(fields: string[], query?: string | null) {
  const q = String(query || '').trim();
  if (!q) return {};
  const regex = new RegExp(escapeRegex(q), 'i');
  return { $or: fields.map((field) => ({ [field]: regex })) };
}
