import bcrypt from 'bcrypt'

const BCRYPT_COST = 12

// Password complexity: min 8 chars, >=1 digit, >=1 upper, >=1 lower
export const validatePasswordComplexity = (plain) => {
  if (typeof plain !== 'string' || plain.length < 8) {
    throw Object.assign(new Error('Password must be at least 8 characters'), {
      code: 'PASSWORD_TOO_SHORT', statusCode: 422,
    })
  }
  if (!/[0-9]/.test(plain)) {
    throw Object.assign(new Error('Password must contain at least one digit'), {
      code: 'PASSWORD_MISSING_DIGIT', statusCode: 422,
    })
  }
  if (!/[A-Z]/.test(plain)) {
    throw Object.assign(new Error('Password must contain at least one uppercase letter'), {
      code: 'PASSWORD_MISSING_UPPERCASE', statusCode: 422,
    })
  }
  if (!/[a-z]/.test(plain)) {
    throw Object.assign(new Error('Password must contain at least one lowercase letter'), {
      code: 'PASSWORD_MISSING_LOWERCASE', statusCode: 422,
    })
  }
}

export const hashPassword = async (plain) => {
  return bcrypt.hash(plain, BCRYPT_COST)
}

export const verifyPassword = async (plain, hash) => {
  if (!hash) return false
  return bcrypt.compare(plain, hash)
}
