import type {
  Request,
  Response,
  NextFunction,
  RequestHandler,
} from 'express';

/** Wraps an async handler so a rejected promise reaches the error middleware. */
export function wrapAsync(
  fn: (req: Request, res: Response, next: NextFunction) => Promise<unknown>,
): RequestHandler {
  return function (req, res, next) {
    fn(req, res, next).catch(next);
  };
}

/** Reads a query-string value as a single string, or undefined. */
export function queryStr(value: unknown): string | undefined {
  return typeof value === 'string' ? value : undefined;
}

/** Reads a query-string value as a finite number, or undefined. */
export function queryNum(value: unknown): number | undefined {
  if (typeof value !== 'string' || value.trim() === '') {
    return undefined;
  }
  const parsed = Number(value);
  return Number.isFinite(parsed) ? parsed : undefined;
}

/** Reads a route param as a single string (params may be string[]). */
export function paramStr(value: string | string[] | undefined): string {
  if (Array.isArray(value)) {
    return value[0] ?? '';
  }
  return value ?? '';
}
