import { body, param, query, validationResult } from 'express-validator';
import currency from '../database/currency.js';

const groupName = body('name').isAscii();

export function getUsersValidation() {
  return [
    query('limit').isInt({ min: 1 }).toInt(),
    query('startsWith').isString()
  ];
}

export function registerAndLoginValidation() {
  return [
    body('username').isAscii().isLength({ max: 50 }),
    body('password').isLength({ min: 5 })
  ];
}

export function groupMemberValidation() {
  return [groupName];
}

export function expenseValidation() {
  return [
    body('description').isString(),
    body('amount').isInt({ min: 0 }),
  ]
}

export function expenseIdValidation() {
  return [param('id').isInt()];
}

export function groupValidation() {
  return [
    groupName,
    body('description').isString().optional(),
    body('currency').isIn(Object.values(currency))
  ];
}

export function groupGetValidation() {
  return [query('closed').isBoolean().optional().toBoolean()];
}

export function validate(req, res, next) {
  const errors = validationResult(req);
  if (errors.isEmpty()) {
    return next();
  }

  return res.status(422).send(errors);
}