import { PAGINATION_LIMITS } from '../constants/limits';
import { ERROR_MESSAGES, ERROR_CODES } from '../constants/errors';

export interface PaginationParams {
  limit: number;
  offset: number;
}

export interface PaginationValidationResult {
  valid: boolean;
  params?: PaginationParams;
  error?: {
    message: string;
    code: string;
  };
}

export const validateAndNormalizePagination = (
  limit?: number | string,
  offset?: number | string
): PaginationValidationResult => {
  const parsedLimit =
    typeof limit === 'string' ? parseInt(limit, 10) : limit ?? PAGINATION_LIMITS.DEFAULT_LIMIT;
  const parsedOffset =
    typeof offset === 'string' ? parseInt(offset, 10) : offset ?? PAGINATION_LIMITS.DEFAULT_OFFSET;

  if (isNaN(parsedLimit) || isNaN(parsedOffset)) {
    return {
      valid: false,
      error: {
        message: ERROR_MESSAGES.INVALID_PAGINATION,
        code: ERROR_CODES.INVALID_PAGINATION,
      },
    };
  }

  if (parsedLimit < PAGINATION_LIMITS.MIN_LIMIT || parsedLimit > PAGINATION_LIMITS.MAX_LIMIT) {
    return {
      valid: false,
      error: {
        message: `Limit must be between ${PAGINATION_LIMITS.MIN_LIMIT} and ${PAGINATION_LIMITS.MAX_LIMIT}`,
        code: ERROR_CODES.INVALID_PAGINATION,
      },
    };
  }

  if (parsedOffset < 0) {
    return {
      valid: false,
      error: {
        message: 'Offset must be non-negative',
        code: ERROR_CODES.INVALID_PAGINATION,
      },
    };
  }

  return {
    valid: true,
    params: {
      limit: parsedLimit,
      offset: parsedOffset,
    },
  };
};
